Search code examples
regexregexp-replace

Remove specific string using RegExp


I have a different string:

Word1-A-OK
Word2-Sample-R-OK
Word3-A

How can remove these (-A, -A-OK, -A-NG, -R, -R-OK, -R-NG, -W, -C) strings using Regexp? The output I would want is:

Word1
Word2-Sample
Word3

This is my current RegExp:

(\\.|-A|[^\w]+R|[^\w]+OK|[^\w]+NG|[^\w]+W|[^\w]+C)  

Solution

  • You seem to be overcomplicating this. Just do a regex replacement on the following alternation:

    -(?:[AR](?:-(?:OK|NG))?|W|C)$
    

    Then, replace with empty string to effectively remove these suffixes.

    Demo