-1

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?

LeWimbes
  • 517
  • 1
  • 10
  • 25

1 Answers1

1

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • "it's the best way" for one definition of best. Most concise, yes. Most readable.... probably not. – Andy Turner Feb 26 '19 at 22:22
  • @Andy although regex is hard to read, it's readable if you are familiar and it's the goto approach for basic (ie non-AST style) "parsing". I would frown on anyone throwing their own code at this kind of problem when regex is a good fit (as here), so you can move on and do something else. – Bohemian Feb 26 '19 at 22:26