Home > Mobile >  How can I catch both matches for this regular expression?
How can I catch both matches for this regular expression?

Time:04-29

I wrote the following regex:

\[url=.*?\/users\/(.*?)\/\]@.*?\[\/url\]|\[quote="(.*?)"\].*?\[\/quote\]

And I'm applying it to the following text with multiline and global modifiers:

[quote="foo"][url=http://localhost:8084/users/bar/]@bar[/url]test[/quote]

Hello World

I would like to match both foo and bar, but it's only matching foo.

Can anyone help?

CodePudding user response:

With your shown samples, attempts; please try following regex.

\[quote="([^"]*)"\]\[url=https?:\/\/[^:]*:[0-9] [^@]*@([^[]*).*?\[\/quote\]

Explanation: Adding detailed explanation for above solution.

\[quote="        ##Matching [quote=" with escaping [ here.
([^"]*)          ##Creating 1st capturing group which has everything just before " in it.
"\]\[url=https?  ##Matching "][url=https? where s is optional and ] and [ are being escaped.
:\/\/[^:]*:      ##matching :// before : everything including : here.
[0-9] [^@]*@     ##matching digits(1 or more occurrences) followed by anything just before @ including @.
([^[]*)          ##Creating 2nd capturing group which has everything just before [ in it.
.*?\[\/quote\]   ##using lazy match .*? to match [quote] where escaping [ and ] here.

CodePudding user response:

You can capture the two strings using a single regex like

\[quote="([^"]*)"\]\[url=[^\]\[]*?\/users\/([^\/]*)\/\]@.*?\[\/url\].*?\[\/quote\]

See the regex demo.

Details:

  • \[quote=" - a fixed string [quote="
  • ([^"]*) - Group 1: any zero or more chars other than "
  • "\]\[url= - a "][url= string
  • [^\]\[]*? - any zero or more chars other than [ and ] as few as possible
  • \/users\/ - /users/ string
  • ([^\/]*) - Group 2: any zero or more chars other than /
  • \/\]@ - /]@ string
  • .*? - any zero or more chars other than line break chars as few as possible
  • \[\/url\] - [/url] string
  • .*? - any zero or more chars other than line break chars as few as possible
  • \[\/quote\] - a [/quote] string.
  • Related