简体   繁体   中英

Regex.Replace - skip strings which are part of a longer string

I need to replace a list of numeric strings in a text file. However, if the string is part of another numeric string it should not be replaced: String to be replaced: 111111 Replacement string: MASKED

Text file:
111111
 111111.text text
text text111111 text text
a111111
2111111
111111a
1111112
a111111a

Expected result:
MASKED
 MASKED.text text
text textMASKED text text
aMASKED
2111111 -> Character 2 prevents masking
MASKEDa
1111112 -> Character 2 prevents masking
aMASKEDa

This is my code:

inputText = Regex.Replace(inputText, "(?<![0-9])" + stringToMask + "(?<![0-9])", "####MASKED####");

This code just skips everything and doesn't perform any masking.

You can use MatchEvaluator http://www.dotnetperls.com/regex-replace to perform replace by condition. To decide preform replace or not you can add first and last letter to match pattern, split string by this pattern and analyze first and last symbols.

If I understand your problem correctly, the following regex should work:

(?<!\d)111111(?!\d)

It uses both a negative lookbehind assertion and a negative lookahead assertion .

Here is a working example .

Output:

MASKED
 MASKED.text text
text textMASKED text text
aMASKED
2111111
MASKEDa
1111112
aMASKEDa

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM