简体   繁体   English

从C#中的字符串中的特定位置删除数字

[英]Remove numbers from a specific place in a string in C#

/abcd1/ef/gh001/d

Read the above line in to a string (String test) 将以上行读入字符串(字符串测试)

I want to remove number after abcd 我想在abcd之后删除号码

The required output is /abcd/ef/gh001/d 所需的输出是/abcd/ef/gh001/d

I have used the following code 我使用了以下代码

test = Regex.Replace(test, "[0-9]", "");

but it removes all the numbers from the line like this 但是它会像这样删除行中的所有数字

/abcd/ef/gh/d

Please help!! 请帮忙!!

Since you know where the digits are, you could make a small adjustment to your expression such that it becomes: test = Regex.Replace(test, "(abcd)[0-9]+", "$1"); 因为您知道数字在哪里,所以可以对表达式进行一些小的调整,使其变为: test = Regex.Replace(test, "(abcd)[0-9]+", "$1"); .

This expression will match abcd1 and place abcd within a group. 此表达式将匹配abcd1并将abcd放在组中。 This group is then accessed later through $1 , so basically you would be replacing abcd1 with abcd . 然后稍后通过$1访问该组,因此基本上您将用abcd替换abcd1

An alternative would be test = Regex.Replace(test, "abcd[0-9]+", "abcd"); 另一种选择是test = Regex.Replace(test, "abcd[0-9]+", "abcd"); , which does the same thing. ,其作用相同。

You can use positive lookbehind to make sure that you are replacing only the numbers that immediately follow abcd : 您可以使用正向后视来确保仅替换abcd的数字:

test = Regex.Replace(test, @"(?<=abcd)\d+", "");

In the example above, one or more digits \\d+ will be matched only if they immediately follow abcd string. 在上面的示例中,仅当一个或多个数字\\d+立即紧跟abcd字符串时,它们才会匹配。

Demo. 演示。

In my my case, the text abcd is not constant - the text could be anything 就我而言,文本abcd不是常数-文本可以是任何东西

example1     /abcd1/ef/gh001/d
example2     /tmcy1/ef/gh001/d

but the location of the string constant. 但是字符串常量的位置。 It always comes at the first between // 它始终位于//之间的第一个

/**abcd1**/ef/gh001/d

You may use the following regex replacement: 您可以使用以下正则表达式替换:

(?i)^(/[a-z]+)\d+(.*)

And replace with $1$2 . 并替换为$1$2

See demo 观看演示

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

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