简体   繁体   中英

C#, Regex & the AND operator

I'm trying to write a regex expression that will produce a match for any string that contains the characters "a", "b" and "c". It must contain them all, but the order does not matter.

"axbxcx" -> true
"cba" -> true
"cbx" -> false

I've tried various methods.

searchRegex = new Regex(("a")("b")("c"))
searchRegex = new Regex("a+b+c+")
searchRegex = new Regex([abc])

The code I'm trying to refactor is this:

return input.Contains("0") && input.Contains("1") && input.Contains("a");

Can this be done?

Gregory

Before going the regex way, note that input.Contains("a") && input.Contains("b") && input.Contains("c") works, is a lot clearer and offers probably better performance.

With that being said, the regular expression (?=.*a)(?=.*b)(?=.*c).* will work for you.

It asserts that the string contains an a , a b and a c and once that is done it matches anything.

The fastest way to do this is use an out of order regex.
Its 3 times faster than either the contains or the pure lookaheads.

(?:.*?(?=[abc])(?:(?(1)(?!))(a)|(?(2)(?!))(b)|(?(3)(?!))(c))){3}

 (?:
    .*? 
    (?= [abc] )
    (?:
       (?(1)(?!)) ( a )                         # (1)
     | (?(2)(?!)) ( b )                         # (2)
     | (?(3)(?!)) ( c )                         # (3)
    )
 ){3}

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