简体   繁体   中英

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". Then i also want to find all possible spellings of it like "AUs", "aUs", "AUS" and so forth. 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 :/

You can make use of lookarounds and a RegexOptions.IgnoreCase flag (or its inline version (?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)
  • aus - literal character sequence aus
  • (?![\\w-[_]]) - check if after aus there is no letter or digit.

A simpler alternative with \\p{L} (any Unicode base letter) and \\p{N} (any digit):

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

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