Regex for matching a string literal in Java?

六眼飞鱼酱① 提交于 2019-11-29 15:42:57

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!