简体   繁体   English

使用Regex.Replace用string.empty替换_x

[英]Replacing _x with string.empty using Regex.Replace

I have a string "region_2>0" where I want to replace _2 with string.empty using Regex. 我有一个字符串“ region_2> 0”,我想用Regex将_2替换为string.empty。

My expression is ((_)[^_]*)\\w(?=[\\s=!><]) which in both Regulator and Expresso gives me _2. 我的表达式是((_)[^_]*)\\w(?=[\\s=!><]) ,在Regulator和Expresso中都给了我_2。 However, the code(c#): 但是,代码(c#):

Regex.Match(legacyExpression, "((_)[^_]*)\\w(?=[\\s=!><])").Value

gives me "_2>0", which also causes the replace to be wrong (It returns "region" since removing the whole "_2>0" instead of "_2". The result I want is "region>0". Shouldn't the code and the regex programs give the same results? And how can I get it to work? 给我“ _2> 0”,这也导致替换错误(它返回“ region”,因为删除了整个“ _2> 0”而不是“ _2”。我想要的结果是“ region> 0”。该代码和regex程序给出的结果相同?如何使它工作?

(Note the string is not static, it could be in many different forms, but the rule is I want to replace the last _X in the string with string.empty. (请注意,该字符串不是静态的,可以采用许多不同的形式,但是规则是我想用string.empty替换字符串中的最后一个_X。

Thanks! 谢谢!

I copied your code as is into the new project: 我将您的代码原样复制到新项目中:

static void Main(string[] args)
{
    var legacyExpression = "region_2>0";
    var rex = Regex.Match(legacyExpression, "((_)[^_]*)\\w(?=[\\s=!><])").Value;
    Console.WriteLine(rex);
    Console.ReadKey();
}

The output is _2 . 输出为_2

我认为这可能有效

(_\d+)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM