Search code examples
javaregexstringreplaceall

Java: How to replace everything except of [0-9] and "sin","cos","tan","ctg", "(" , ")" in String


I need to replace all characters in a string except these ones : [0-9] and "sin", "cos", "tan", "ctg", "(" , ")"

I think I need to use String.replaceAll("some regex","") but can't figure right regex.

For example, if I have this String: 123321323n3k332313jbj323sin232323jkjctg2323. I need to get this one after replacing : 1233213233332313323sin232323ctg2323

Need to replace bad characters with empty characters ""

solution: String.replaceAll("(c(?:os|tg)|sin|tan)|[^0-9\\(\\)]","$1"); thanks to Krayo


Solution

  • I think what you are looking for is this:

    (c(?:os|tg)|sin|tan)|[^0-9)(]
    

    with this replacement string:

    $1
    

    The content between parentheses is tested first and captured. $1 is the reference to this capture. If the contents of those parentheses is not matched, then nothing is captured and the $1 reference resolved to the empty string.

    (?:...) delimits only a non capturing group, useful for the two possibilities os and tg after a c.

    To translate in plain English what this regex does: replace anything that isn't digits or parentheses with

    • itself if it is one of "cos", "sin", "tan" or "ctg"
    • nothing otherwise.