1

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?

1
  • Are you trying to remove everything after the last underscore (including)? Commented May 25, 2016 at 15:07

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

5 Comments

[_L]{2} will match: LL L_ and __ aswell.
@lbarros I know but I didn't have the time to write it down ;)
@ThomasAyoub Ok ;)
How to make it detect _L01 or _L1 with a maximum of 2 digits?
Thanks! Worked like a charm ^^
1

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 

Comments

0

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}";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.