简体   繁体   中英

RegEx match on any of multiple groups

I'm not sure if this is possible, but I would like to match on multiple regex groups

(^[0-9]) (^[$][0-9]) (^[$]{2}[0-9])

It would match the string if the first character is number, or if the first character is a $ followed by a number, or if the first two characters are a $ followed by a number.

Example strings that would match:

15271%
$3C001%
$$8244150928223C001%

Can this be done in one go, or would I have to check each match individually?

Any help is appreciated. Thanks!

You could use:

^\d.*|^\$\d.*|^\$\$\d.*


try {
    if (Regex.IsMatch(subjectString, @"\A(?:^\d.*|^\$\d.*|^\$\$\d.*)\z", RegexOptions.Multiline)) {
        // Successful match
    } else {
        // Match attempt failed
    } 
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

You can make make use of the pipe symbole | to achieve that. It basically behaves like an "or" in your regex pattern.

For example:

(banana|apple)

would match both "banana" and "apple".

In your case, you can also use a pattern like this

(\${0,2}\d.+)

to match all options: without $, with one $ and with two $.

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