Yadheendran Yadheendran - 2 months ago 6
Perl Question

Regex - Match string that with : and space

I have below possible strings and i need to match specific chars.

Possible String to match:

dsg.1.2.3.4.5.6.7.5 = STRING: 1234 blah blah blah

OR

dsg.1.2.3.4.5.6.7.5 = STRING: "1234 blah blah blah"


Below is the Regex that i have tried. It is working but for the 1st string, It is matching with " "

\=\s*STRING\:\s(?=\")\"([^"]*)|([^:]*$)


To match the above possible string, I used if condition that match well for the
dsg.1.2.3.4.5.6.7.5 = STRING: "1234 blah blah blah"


Not the
dsg.1.2.3.4.5.6.7.5 = STRING: 1234 blah blah blah


Output issue after match:

2. [29-58] ` 1234 blah blah blah`


output needed:

1. [29-58] `1234 blah blah blah` --> No space


Please help me on this issue.

Answer

In perl (PCRE) you can use a regex using (?|...) non-capturing group construct:

/=\s*STRING:\s(?|"([^"]*)|([^:]*))/

RegEx Demo

(?|...) - Subpatterns declared within each alternative of this construct will start over from the same index.

This regex will match 1234 blah blah blah in the captured group #1 for both input lines.

Comments