Reputation: 1
/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
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
Reputation: 627380
You may use the following regex replacement:
(?i)^(/[a-z]+)\d+(.*)
And replace with $1$2
.
See demo
Upvotes: 0
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.
Upvotes: 1
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