简体   繁体   English

C#中的正则表达式:匹配在“ _”或“”或“”之前和/或之后的字符串

[英]Regex in C#: match string thats preceded and/or followed by “_” or “ ” or “”

lets assume i have a word like "aus" and i want to replace all occurences of it with "off". 假设我有一个像“ aus”的词,我想用“ off”代替它的所有出现。 Then i also want to find all possible spellings of it like "AUs", "aUs", "AUS" and so forth. 然后,我还想找到它的所有可能的拼写,例如“ AU”,“ aUs”,“ AUS”等等。 But its important that its only replaced when it "stands alone" as in has only a space, an underscore (_) or nothing in front and/or after it so it should be replaced in 但重要的是,只有当它“单独站立”时才被替换,因为它只有空格,下划线(_)或前后没有空格,因此应在其中替换

" aus"
"aus"
"_aus"
"_aus_"
"aus_"

But not in 但不在

"ausschalten"
"aushebeln"
" ausschalten"

I tried ^(_| )(A|a)(U|u)(S|s)(_|)$ but its not working right :/ 我尝试了^(_| )(A|a)(U|u)(S|s)(_|)$但是它不能正常工作:/

You can make use of lookarounds and a RegexOptions.IgnoreCase flag (or its inline version (?i) ): 您可以使用RegexOptions.IgnoreCaseRegexOptions.IgnoreCase标志(或其内联版本(?i) ):

@"(?i)(?<![\w-[_]])aus(?![\w-[_]])"

See regex demo 正则表达式演示

Explanation : 说明

  • (?<![\\w-[_]]) - check if before aus there is no digit or letter character (using character class subtraction , I removed _ from \\w class) (?<![\\w-[_]]) -检查在aus之前是否没有数字或字母字符(使用字符类减法 ,我从\\w类中删除了_
  • aus - literal character sequence aus aus文字字符序列aus
  • (?![\\w-[_]]) - check if after aus there is no letter or digit. (?![\\w-[_]]) -检查aus之后是否没有字母或数字。

A simpler alternative with \\p{L} (any Unicode base letter) and \\p{N} (any digit): \\p{L} (任何Unicode基本字母)和\\p{N} (任何数字)的更简单替代方法

(?i)(?<![\p{L}\p{N}])aus(?![\p{L}\p{N}])

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

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