Search code examples
htmlswiftregextoken

Swift Regex to retrieve token from a page html


I have a page html like this :

<!DOCTYPE html>
   <html>
  <head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="viewport" content="width=device-width, initial- 
    scale=1"/>
    <title>Odoo</title>
    <link type="image/x-icon" rel="shortcut icon" 
   href="/web/static/src/img/favicon.ico"/>
    <script type="text/javascript">
                var odoo = {
                    csrf_token: 
    "999b60e0c81591c5909866b2421e01ff397bcc16o",
                };
             </script>
       <meta name="theme-color" content="#875A7B"/>

I want to retrieve the value of csrf_token how can I do that, please ?

I tried something like that

let a = text!.matchingStrings(regex: "\"csrf_token\":([A-z0-9]*")

with

extension String {
  func matchingStrings(regex: String) -> [[String]] {
     guard let regex = try? NSRegularExpression(pattern: regex, 
  options: []) else { return [] }
    let nsString = self as NSString
    let results  = regex.matches(in: self, options: [], range: 
  NSMakeRange(0, nsString.length))
    return results.map { result in
        (0..<result.numberOfRanges).map {
            result.range(at: $0).location != NSNotFound
                ? nsString.substring(with: result.range(at: $0))
                : ""
        }
    }
    }
  }

But it doesn't work.

Any help would be appreciated.

EDIT

like @Pushpesh Kumar Rajwanshi suggest the solution is

let regex = try NSRegularExpression(pattern: "\"csrf_token\":([A-z0-9]*")


Solution

  • Why are you enclosing csrf_token in double quotes when in your string it is not enclosed with it. Also there seems to be a space after csrf_token: hence your regex isn't working. You can use this regex,

    csrf_token:\s*"([^"]*)"
    

    And capture group1 for extracting the text for csrf_token attribute. In your language you may have to escape " like you did in your regex.

    Demo