Michelle
Michelle

Reputation: 693

Conditionally select a single character in regex using lookahead/lookbehind?

I am making a code-cleanup tool that will automatically format my code to my company's C++ code style standards. One such standard is that method names must have a space before the (.

void Method (...);

I want to use a regex to match such parentheses so that I may replace ( with (.

Since this is only for method signatures, I want to ignore strings such as if(...), while(...), etc.

My idea is to use a negative lookahead to make sure that the line doesn't contain a "C++ word"

^(?!if|for|switch|do|while).+(\()

and use a negative lookbehind to make sure that the ( is not preceded by a space.

(?<! )\(

These do the trick individually, but I am having difficulty combining them. Firstly, is this a reasonable approach? Is there a better way?

More importantly, how can I select my (?

Upvotes: 1

Views: 65

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174756

You need to use a negative lookbehind assertion.

(?<!\b(if|for|switch|do|while))\(

or

(?<!\bif|\bfor|\bswitch|\bdo|\bwhile)\(

or

(?<!\s)(?<!\bif|\bfor|\bswitch|\bdo|\bwhile)\(

Replace with:

 (

DEMO

Upvotes: 1

Related Questions