7

I am new to regular expressions, and I am just tired by really studying all of the regex charatcer and all. I need to know what is the purpose of greater than symbol in regex for eg:

preg_match('/(?<=<).*?(?=>)/', 'sadfas<email@email.com>', $email);

Please tell me the use of greater than symbo and less than symbol in regex.

peterh
  • 11,875
  • 18
  • 85
  • 108
badu
  • 999
  • 3
  • 9
  • 11

2 Answers2

17

The greater than symbol simply matches the literal > at the end of your target string.

The less than symbol is not so simple. First let's review the lookaround syntax:

The pattern (?<={pattern}) is a positive lookbehind assertion, it tests whether the currently matched string is preceded by a string matching {pattern}.

The pattern (?={pattern}) is a positive lookahead assertion, it tests whether the currently matched string is followed by a string matching {pattern}.

So breaking down your expression

  • (?<=<) assert that the currently matched string is preceded by a literal <
  • .*? match anything zero or more times, lazily
  • (?=>) assert than the currently matched string is followed by a literal >

Putting it all together the pattern will extract email@email.com from the input string you have given it.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
3

Your regex is using lookarounds to capture email address between < and > characters. In your example input it captures email@email.com.

Explanation:

(?<=<) Positive Lookbehind - Assert that the regex below can be matched
< matches the character < literally
.*? matches any character (except newline)
Quantifier: Between zero and unlimited times, as few times as possible,
expanding as needed [lazy]
(?=>) Positive Lookahead - Assert that the regex below can be matched
> matches the character > literally

Online Demo: http://regex101.com/r/yH6tY8

anubhava
  • 761,203
  • 64
  • 569
  • 643