RegEx

Last Updated Jul 09, 2021

What is RegEx?

RegEx is shorthand for "regular expression". It defines a pattern for searching or manipulating strings. For example, if you were looking for the word "gray", but wanted to search both possible spellings ("gray" and "grey") with one search, you could use the regular expression `«gr[ae]y» ` to search for both words at once.  

How is RegEx Useful?

"So what?" you might be thinking. "Looks like some old-school database stuff."

Well, what if I told you that this regular expression `«\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b»` can be used to validate an email?. Imagine all the code it would take to validate an input as an email address without a regex string. Regex is a handy tool to keep in your toolkit as a web developer, especially its `-g` flag to check results globally.

Some other use cases where RegEx's string-matching capabilities can help:

  • Validate a domain name: ` $url = "http://abstractapi.com/"; if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i', $url)) {     echo "Your url is ok."; } else {     echo "Wrong url."; } `
  • Remove ~~repeated words~~ repeated words: ` $text = preg_replace("/s(w+s)1/i", "$1", $text); `
  • Find and print the information in the `<title> </title>` tag on a website: ` $fp = fopen("https://abstractapi.com","r");  while (!feof($fp) ){     $page .= fgets($fp, 4096); }  $titre = eregi("<title>(.*)</title>",$page,$regs);  echo $regs[1]; fclose($fp); `

Regex and JSON

Where is another place we see text in API development? The JSON file. We can validate API responses using Regex:


var body = JSON.parse(context.response.body);

assert( body.transcript.search(/example.*/i) > -1, 
              "transcript field does not contain 'faux'");

In this case, the RegEx is in parentheses behind `search`. We are looking for the word `example`, and the other characters in the parentheses are RegEx query parameters.

`.` means that `example` must be followed by at least one character.
`*` means that any number of characters can follow `example`.
`i` means that the search is not case sensitive.

If our query tells us the word `example` was not found, and `example` `was a resource we are depending upon, this test will tell us the resource is down.  

Conclusion

RegEx is difficult to get into, but extremely powerful once it's understood, because it's like a programming language inside another programming language. You can even call it as an API.