简体   繁体   中英

Regex with a match between quotes

I tried to find a solution to my RegEx problem, but I cannot find an answer.

My target string is like this:

"Elevator" <sip:103@192.168.1.1>;tag=343483547

I want my matching groups to be: - Elevator - 103

But when I use this regex:

"(.*)"?<sip:(\d*)@.*

then I get an unwanted quote with my 1st match. It results in: - Elevator" - 103

I can't get it to work. I tried the most obvious things like

"([^"]*)"?<sip:(\d*)@.*

but then the first match vanishes completely

What am I doing wrong.

You are making the " optional and the .* is greedy matching until the < is encountered.

If the quote is unwanted, you could update it to make the " not optional and match the space before the < .

The "(.*?)" part can also be matched as ([^"]+)

If you want to match 1 or more digits use \\d+

"(.*?)" <sip:(\d+)@

Regex demo (Click on the Table tab)

You need to account for the whitespace between an optional " and the following < char.

Use

"([^"]*)"?\s*<sip:(\d*)@.*

See the regex demo

Details

  • " - a " char
  • ([^"]*) - Group 1: any zero or more chars other than "
  • "? - an optional " char
  • \\s* - 0+ whitespaces
  • <sip: - <sip: substring
  • (\\d*) - Group 2: zero or more (replace * with + to match one or more) digits
  • @.* - a @ and the rest of the line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM