1

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I get a FormatException when I use this above pattern/C# statement, could you please help me out?
Sorry, I always remember to double the curly braces with limiting quantifiers, and forgot to do the same with the Unicode category class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.