Johnson Zhou
Johnson Zhou

Reputation: 493

How to carry out optional leading word match in regex

I'm quite new to the use of regex. I'm building a word parser and I need to replace line segments, which could show up as AB or Line AB, into Line(AB). I have checked out regex optional word match, but in my case the leading Line word is optional, when I use (?:[Ll]ine)?\b([A-Z])([A-Z]) the engine just replaces the AB and it becomes Line Line(AB).

Any help would be greatly appreciated.

Upvotes: 0

Views: 87

Answers (1)

The fourth bird
The fourth bird

Reputation: 163217

You could optionally match Line and capture AB in a group.

\b(?:[Ll]ine )?(AB)\b

Int he replacement use Line followed by the capturing group $1 or \1 between parenthesis.

Line ($1)

Regex demo

Or with multiple uppercase chars instead of AB only

\b(?:[Ll]ine )?([A-Z]+)\b

Regex demo

Upvotes: 1

Related Questions