Mirko Pagliai
Mirko Pagliai

Reputation: 1241

Regex to add prefix

I have this string:

ab ab-alfa beta gamma ab-delta

I would like to add the prefix "ab-" to every word, except for the words that already have it and except for the word "ab" (the first one).

I mean, I would get this result:

ab ab-alfa ab-beta ab-gamma ab-delta

You know indicate a regex and explain it?

-- edit

So far I've tried this (link):

\b(?!ab)\w+\b

But I don't think I understand how the negation works.

Upvotes: 1

Views: 9131

Answers (2)

Ron Rosenfeld
Ron Rosenfeld

Reputation: 60174

Try this for the regex

(?<!ab-)(?!\bab\b)\b\w+\b

And this for the replacement string

ab-$&

Upvotes: 0

nhahtdh
nhahtdh

Reputation: 56809

You may use this regex:

(?<![^ ])(?=[^ ])(?!ab)

with the replacement ab-.

(?<![^ ])(?=[^ ]) will search for the boundary of the beginning of a word (which is defined to be a sequence of non-space characters).

In general, given a character class for "word character"s C, a general "word boundary" (similar to \b) would be:

(?:(?<!C)(?=C)|(?<=C)(?!C))

The boundary for the beginning of a "word" would be:

(?<!C)(?=C)

The boundary for the end of a "word" would be:

(?<=C)(?!C)

This ensures that "word boundary" is not found on empty string, and a "word boundary" is found if a "word character" is at the beginning or the end of the string.


Note that (?<= )(?! ) at first glance may look like an equivalent pattern to (?<![^ ])(?=[^ ]), but it is not, since it fails to match the beginning of a word when the word appears at index 0 in a string.

Also, don't try to shorten it to (?<![^ ])(?!ab| ), it will return a match when the string is empty.

Upvotes: 2

Related Questions