" in a letter In the next line Jason < [email protected] > How can I extract a part inside ...">

Regular expressions: how to find a bit between "<>" in a letter

In the next line

Jason < [email protected] >

How can I extract a part inside angle brackets. I tried <\ w> and it did not work.

Ideas? I use preg_match () in php if that matters.

+4
source share
2 answers

Use <(.*?)> As a regular expression, then.

+7
source

user502515 already provided you a regex.

I would like to add why your regex <\w> did not work:

\w is short for the character class [a-zA-Z0-9_] and matches any character in one of this class. To match more characters, you need to use quantifiers:

  • + for one or more and
  • * for zero or more

Since you want to extract a string that matches the pattern, you need to enclose the pattern in brackets (..) so that it is captured.

Now your initial task was to extract the line between <..> , regex <(\w+)> will not do the job, since the class char \w does not include @ .

To match all, you use the regular expression .* , Which matches any arbitrary line (without a new line).

So regex <(.*)> Matches and commits any line between angular brackets.

The match is greedy, so if the input line is foo< [email protected] >, bar<bar.com> , you will retrieve [email protected] >, bar<bar.com . To fix this, you make the match not greedy by adding ? at the end .* , giving us the correct regular expression <(.*?)>

+15
source

All Articles