user5139771
user5139771

Reputation: 1

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!!

Upvotes: 0

Views: 397

Answers (4)

user5139771
user5139771

Reputation: 1

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

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627380

You may use the following regex replacement:

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

And replace with $1$2.

See demo

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

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.

Upvotes: 1

npinti
npinti

Reputation: 52185

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.

Upvotes: 3

Related Questions