Home > Software engineering >  Regex ignore the line with underscore
Regex ignore the line with underscore

Time:07-28

Regex.Match(line, "^\[(\w )[^_]]")

When the string contains underscore, I would like no match.

Example:

Line 1: [String] returns String

Line 2: [String_Ab] returns String_AB.

I would like to return line 1 match String removing the brackets. Skip Line 2 because the string contains underscore. Right now "^\[(\w )[^_]]"), returns String and String_AB.

CodePudding user response:

As a pattern to get a match only between square brackets without matching an underscore, you might use:

(?<=\[)[^][_]*(?=])

Explanation

  • (?<=\[) Assert [ to the left
  • [^][_]* Match optional chars other than [ ] and _
  • (?=]) Assert ]` to the right

Regex demo

Or using a capture group

\[([^][_]*)]

Regex demo

  • Related