问题
I have a Regex that match multiple option.
E.g. ^0x[\da-fA-F]+|-?\d+$ -- a Regex for Match either decimal or hex literals
Is there an option to know which option was eventually match the pattern?
so for...
-10- the decimal option was matched0x1Af- the hex option was matched
回答1:
I think you meant this regex:
^(?:-?\d+|0x[\da-fA-F]+)$
with the start and end anchors not part of the alternatives.
You can capture the different alternatives:
^(?:(-?\d+)|(0x[\da-fA-F]+))$
Now you just need to check if a group is not null. If it matches the first alternative, group 1 will be non-null. If it matches the second alternative, group 2 will be non-null:
Match m = Regex.Match(...);
if (m.Groups[1] != null) {
// first alternative matched!
} else if (m.Groups[2] != null) {
// second alternative matched!
}
You can also name your groups to make your code more readable:
^(?:(?<decimal>-?\d+)|(?<hex>0x[\da-fA-F]+))$
Now you should check for m.Groups["decimal"] and m.Groups["hex"].
来源:https://stackoverflow.com/questions/55136945/how-to-know-which-option-in-regex-was-matched