Match a line having particular text and ending with _P within square brackets

Viewed 99

I have several lines of texts, for example, two of them below:

a[15].s16.l = (xy[11].s16.l > (50/*QUE-const:VECTWord->CC_Init_P*/))

xyz = Exh[(16/*QUE-const:VECT_dir->_num_P*/) & 0x0FU ];*/))

I want to match the line which is having "QUE-const" and ends with "_P" within square brackets [].

I wrote following regex:

\[.*QUE-const.*_P.*

but it is matching both the lines, rather it should match only second line.

Please check and coorect where I'm going wrong.

3 Answers

With your shown samples, could you please try following.

\[.*?QUE-const.*?_P.*?\]

Here is Online demo for above regex

Explanation: Adding detailed explanation for above.

\[.*?QUE-const.*?_P.*?\]
##Matching [ and till QUE-const then match till _P(with non-greedy quantifier) till first occurrence of ] here.

I believe you were close. Here's my take on it:

^.*\[.*QUE-const.*_P.*\].*$

Regex Demo

Explanation:

^                      # start of line
.*                     # match anything 0 to unlimited times
\[                     # match bracket 1
  .*QUE-const.*        # match string containing QUE-const ... 
  _P.*                 # ends on _P and !!! anything after (in your example that should match you have */ after _P ) 
\]                     # match bracket 2
.*                     # match anything after 0 to unlimited times
$                      # end of line

You could also use negated character classes starting with [^][]* to not pass the square bracket boundaries while matching the text.

\[[^][]*QUE-const[^][]*_P[^][]*]

Regex demo

Or if you want to match the whole line:

^.*?\[[^][]*QUE-const[^][]*_P[^][]*].*$

The pattern matches:

  • ^ Start of string
  • .*? match any char as least as possible
  • \[[^][]* Match the opening [ and then 0+ times char except [ and ]
  • QUE-const Match literally
  • [^][]* Match 0+ times any char except [ and ]
  • _P Match literally
  • [^][]*] Match 0+ times any char except [ and ] and then match the closing ]
  • .* Match 0+ times any char
  • $ End of string

Regex demo

Related