bigSloppy
bigSloppy

Reputation: 65

Regex not finding the beginning of a string

I have the following input string: "winslow homer harper weekly \"sharpshooter picket duty\" original"

The following regex expression:

(?<ModBroadBeg>.+)(?<modBroadWord>(^| )*winslow *)(?<ModBroadEnd>.*)

The following regex/replace expression:

${ModBroadBeg}+${modBroadWord}${ModBroadEnd}

And the following C# code. I want to replace "winslow" with "+winslow"

NewKeyWordOutString = Regex.Replace(NewKeyWordOutHoldString, BuildKeywordReplaceStruct, ReplaceModBroadWord);

I tested this in RegexBuddy and it works. The above code works with homer, harper and weekly. Leading me to believe there is a problem with "winslow" because it is the beginning of the string. I tested in Visual Studio and if I place a space in front of "winslow" the regex works.

Upvotes: 1

Views: 71

Answers (1)

JDB
JDB

Reputation: 25810

(?<ModBroadBeg>.+)(?<modBroadWord>(^| )*winslow *)(?<ModBroadEnd>.*)

This expression is going to match an input which has one or more characters (.+) followed by either zero or more starts of the input (which is impossible) or spaces ((^| )*) followed by winslow with zero or more trailing spaces (winslow *) followed by zero or more characters (.*).

Basically, this is not going to match an input that starts with winslow.

If you simple want to replace all instances of winslow with +winslow, then you can just use:

(?=winslow)

which uses a zero-width positive lookahead assertion to match the position before winslow, and replace the zero-length string with + (which is, effectively, a way to insert content at a specific point).

If you want to match the "winslow" in foo winslow bar but not in foowinslow bar or foo winslowbar, then you can use word boundaries (\b) to match the beginning/end of a word, like so:

(?=\bwinslow\b)

Word boundaries are use to detect when the character on one side of the boundary is whitespace and the character on the other side is not. They also work when word is bounded by the beginning or end of input, such as winslow foo bar and foo bar winslow.

Upvotes: 1

Related Questions