How to know which option in Regex was matched?

我只是一个虾纸丫 提交于 2021-02-11 14:32:24

问题


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 matched
  • 0x1Af - 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!