我有相当多的 RegEx 知识,但我被这个难住了。我需要一个正则表达式来匹配最后一个下划线之前的所有内容,但仅如果下划线之后的文本是“self”、“ally”或“enemy”。
所以如果我有这样的输入字符串:
"hero_anti_infantry_melee_2_self"
"anti_infantry_ranged_2_ally"
"suppression_aoe_enemy"
"reinforce_btn_down"
"inset_energy"
"suppressed"
我希望它们输出为:
"hero_anti_infantry_melee_2"
"anti_infantry_ranged_2"
"suppression_aoe"
//No Match (not match because it isn't enemy, ally, or self after the underscore)
//No Match
//No Match (not underscores or enemy/ally/self
这是使用 C# RegEx 引擎,它可以使用任何必要的 RegEx 选项。
最佳答案
您需要的是前瞻性。这样的事情应该有效:
new Regex(@"^.*(?=_(ally|self|enemy)$)")
(?=
...)
表示 pretty much what you wanted :
Zero-width positive lookahead. Matches at a position where the pattern inside the lookahead can be matched. Matches only the position. It does not consume any characters or expand the match. In a pattern like one(?=two)three, both two and three have to match at the position where the match of one ends.
编辑:MSDN 有 better examples为此。
关于c# - 匹配下划线前所有内容的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4447125/