Sonhja
Sonhja

Reputation: 8448

How to replace a pattern using Regex?

Before anything, I've googled this question, and I found the solution (apparently). But I can't make it work. So my question is more "Why is this wrong..." more than "How to make this..."

I wrote this code:

private const string pattern = @"^[_L]{2}[0-9]{2}$";
public string RemoveL(string child)
{
    Regex regex = new Regex(pattern);
    return regex.Replace("SUB_1_SC_0310_1_A_L01", "");
}

This code tries to remove L_XX from any string. So:

SUB_1_SC_0310_1_A_L01 --> SUB_1_SC_0310_1_A

But it returns the same string SUB_1_SC_0310_1_A_L01.

Any idea on what I'm doing wrong?

Upvotes: 1

Views: 95

Answers (3)

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

This is wrong because you used ^$ which means start & end of string. Change your regex to [_L]{2}[0-9]{2} and it will works.

Note that you can use \d instead of [0-9] and [_L]{2} will match any combination of _ and L, prefer _L instead.

I would use _L\d{2}.

It seems that you want to make the second digit optional. You have a few options:

  • _L\d\d? <= The ? make the second digit optional;
  • _L\d{1,2} <= {a,b} ensure that the previous pattern is present from a to b times (inclusive)

Upvotes: 3

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

The right pattern is

    private const string pattern = @"_L[0-9]{2}$";

Notice absence of ^ (string has no need to start with [_L]) and {2} after _L (you want just "_L", not any of {_, L} set twice).

Explanation:

   _L       - exactly _L
   [0-9]{2} - exactly 2 digits 0..9  
   $        - end of string 

If you want to replace "xxxxL_01" (please, notice L and _ order) as well then

    private const string pattern = @"[_L]{2}[0-9]{2}$";

Explanation:

   _L       - '_' and 'L' in any order (i.e. either _L or L_)
   [0-9]{2} - exactly 2 digits 0..9  
   $        - end of string 

Upvotes: 1

pierroz
pierroz

Reputation: 7870

the problem in your pattern are the characters '^' and '$' which say match the beginning and the end of the string. If you remove them, your pattern will match the string _L01, for instance, anywhere in the string.

so your pattern should be

private const string pattern = @"[_L]{2}[0-9]{2}";

Besides if you use [_L] it means one element of the class composed of the characters '_' and 'L'. It will match "_L" but also "__", "L_", or "LL". If you want to be more restrictive and match only "_L" your pattern should be

private const string pattern = @"_L[0-9]{2}";

Upvotes: 0

Related Questions