Sandepku
Sandepku

Reputation: 861

Regex pattern to replace a string

I have the following input:

Person 1kg

To get the expected output:

Person 1kEq

I am using the following pattern:

string.Format(@"(?<!\S){0}(?!\S)", Regex.Escape("kg"));
Regex.Replace(inputSentence, Pattern, "kEq");

The Regex.Replace does not replace kg with kEq.

If I edit the input sentence to Person 1 kg the replacement happens,

Could someone help me with the pattern for this?

Upvotes: 1

Views: 96

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

The (?<!\S) requires either a start of the string or a whitespace before the kg search term. The (?!\S) lookahead requires the end of string or a whitespace after the search term. That is why the replacement happens if you separate the number and the measurement unit with a space as in Person 1 kg.

It seems in this case, you want to replace a match if it is not enclosed with other letters. Use (?<!\p{L}) lookbehind at the start and (?!\p{L}) lookahead at the end:

string.Format(@"(?<!\p{{L}}){0}(?!\p{{L}})", Regex.Escape("kg"));

See the regex demo.

Upvotes: 3

Related Questions