java关于行的正则表达式包含多个字符
问题描述:
Iam新增了java,我想提出一个关于java正则表达式的问题。java关于行的正则表达式包含多个字符
如何检查一行只包含特定的字符串,然后是任何操作符。另外,以前的字符串不包含“//”。
例如,如果线是:预先
//x; -> does not matches the criteria
x++; ->matches
x--; ->matches
x=1; ->matches
(x,y) ->matches
(x1,y) ->does not matches because we want only x not x1
x = 1 ; ->matches
感谢。
答
您可以使用该负前瞻基于正则表达式:
^(?:(?!//).)*\bx\b.*
在Java中使用:
boolean valid = str.matches("^(?:(?!//).)*\\bx\\b");
正则表达式破碎:
^ # line start
(?:(?!//).)* # negative lookahead, match any char that doesn't have // at next position
\b # word boundary
x # literal x
\b # word boundary
.* # match every thing till end
这对于_parser_来说看起来更好。你的项目是关于什么的? –