简体   繁体   中英

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

The required output is /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"); .

This expression will match abcd1 and place abcd within a group. This group is then accessed later through $1 , so basically you would be replacing abcd1 with abcd .

An alternative would be 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 :

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.

Demo.

In my my case, the text abcd is not constant - the text could be anything

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 .

See demo

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