Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Match string that with : and space

Tags:

regex

perl

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.

like image 985
Raja Avatar asked Jan 06 '23 09:01

Raja


2 Answers

Try this regular expression:

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

There is no need to use look-aheads, just use ("?) to match the quote (if it exists) and then use a backreference to match it again in the end. The string after STRING will be stored in $2.

like image 53
redneb Avatar answered Jan 14 '23 04:01

redneb


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.

like image 39
anubhava Avatar answered Jan 14 '23 05:01

anubhava