简体   繁体   English

Regex.Replace-跳过较长字符串中的字符串

[英]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 但是,如果该字符串是另一个数字字符串的一部分,则不应替换:要替换的字符串:111111替换字符串: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. 您可以使用MatchEvaluator http://www.dotnetperls.com/regex-replace进行条件替换。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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