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?
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.