Search code examples
javastringcontainsmetacharacters

String contains any but one character


I want to check if a String contains a } with any character in front of it except \. As far as I know I can use . as a metacharacter in aString.contains(...) to allow any character at that position but I don’t know how to create something like a blacklist: aString.contains(“.(except ‘\‘)}“Is that possible without creating an own method?


Solution

  • You need regex (well technically you don't need regex, but it's the best way):

    if (aString.matches(".*(?<!\\\\)}.*"))
    

    This regex says the string should be made up as follows

    • .* zero or more of any character
    • (?<!\\\\) the previous char is not a backslash
    • } a curly right bracket
    • .* zero or more of any character

    This also works for the edge case of the first char being the curly bracket.

    See live demo.