简体   繁体   中英

Regex to remove specific string if exist

I wanna remove the -L from the end of my string if exists

So

ABCD   => ABCD
ABCD-L => ABCD

at the moment I'm using something like the line below which uses the if/else type of arrangement in my Regex, however, I have a feeling that it should be way more easier than this.

var match = Regex.Match("...", @"(?(\S+-L$)\S+(?=-L)|\S+)");

How about just doing:

Regex rgx = new Regex("-L$");
string result = rgx.Replace("ABCD-L", "");

So basically: if the string ends with -L , replace that part with an empty string.

If you want to not only invoke the replacement at the end of the string, but also at the end of a word, you can add an additional switch to detect word boundaries ( \\b ) in addition to the end of the string:

Regex rgx = new Regex("-L(\b|$)");
string result = rgx.Replace("ABCD-L ABCD ABCD-L", "");

Note that detecting word boundaries can be a little ambiguous. See here for a list of characters that are considered to be word characters in C#.

You also can use String.Replace() method to find a specific string inside a string and replace it with another string in this case with an empty string.

http://msdn.microsoft.com/en-us/library/fk49wtc1(v=vs.110).aspx

Use Regex.Replace function,

Regex.Replace(string, @"(\S+?)-L(?=\s|$)", "$1")

DEMO

Explanation:

(                        group and capture to \1:
  \S+?                     non-whitespace (all but \n, \r, \t, \f,
                           and " ") (1 or more times)
)                        end of \1
-L                       '-L'
(?=                      look ahead to see if there is:
  \s                       whitespace (\n, \r, \t, \f, and " ")
 |                        OR
  $                        before an optional \n, and the end of
                           the string
)                        end of look-ahead

You certainly can use Regex for this, but why when using normal string functions is clearer?

Compare this:

text = text.EndsWith("-L")
    ? text.Substring(0, text.Length - "-L".Length)
    : text;

to this:

text = Regex.Replace(text, @"(\S+?)-L(?=\s|$)", "$1");

Or better yet, define an extension method like this:

public static string RemoveIfEndsWith(this string text, string suffix)
{
    return text.EndsWith(suffix)
        ? text.Substring(0, text.Length - suffix.Length)
        : text;
}

Then your code can look like this:

text = text.RemoveIfEndsWith("-L");

Of course you can always define the extension method using the Regex. At least then your calling code looks a lot cleaner and is far more readable and maintainable.

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