Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for matching a string literal in Java?

I have an array of regular expressions strings. One of them must match any strings found in a given java file.

This is the regex string I have so far: "(\").*[^\"].*(\")"

However, the string "Hello\"good day" is rejected even though the quotation mark inside the string is escaped. I think what I have immediately rejects the string literal when it finds a quotation mark inside regardless of whether it is escaped or not. I need it to accept string literals with escaped quotes but it should reject "Hello"Good day".

  Pattern regex = Pattern.compile("(\").*[^\"].*(\")", Pattern.DOTALL);
  Matcher matcher = regex.matcher("Hello\"good day");
  matcher.find(0); //false
like image 533
pythonbeginner4556 Avatar asked Dec 01 '22 16:12

pythonbeginner4556


1 Answers

In Java you can use this regex to match all escaped quotes between " and ":

boolean valid = input.matches("\"[^\"\\\\]*(\\\\.[^\"\\\\]*)*\"");

Regex being used is:

^"[^"\\]*(\\.[^"\\]*)*"$

Breakup:

^             # line start
"             # match literal "
[^"\\]*       # match 0 or more of any char that is not " and \
(             # start a group
   \\         # match a backslash \
   .          # match any character after \
   [^"\\]*    # match 0 or more of any char that is not " and \
)*            # group end, and * makes it possible to match 0 or more occurrances
"             # match literal "
$             # line end

RegEx Demo

like image 175
anubhava Avatar answered Dec 03 '22 06:12

anubhava