c# - 匹配下划线前所有内容的正则表达式

标签 c# .net regex c#-4.0

我有相当多的 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/

相关文章:

.net - 从 C# 应用程序控制其他窗口

java - 使用java正则表达式模式获取部分匹配字符串

c# - 在 LINQ 中选择计数

.net - 禁用 Windows 窗体上的所有事件

c# - 如何使用 C# 和 SMO 终止与 SQL Server 数据库的所有连接?

Java正则表达式单词提取排除特殊字符

c# - 模式匹配和占位符值

c# - 工作框架;在代码隐藏中在路径标记语法和几何图形之间转换

c# - 如何在 PLinq ForAll 中获取元素索引

c# - 看不懂的语法,从vc++到c#