简体   繁体   中英

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.

My expression is ((_)[^_]*)\\w(?=[\\s=!><]) which in both Regulator and Expresso gives me _2. However, the code(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?

(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.

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 .

我认为这可能有效

(_\d+)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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