[英]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
字符串时,它们才会匹配。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.