简体   繁体   English

关于行的Java正则表达式包含多个字符

[英]java Regular expressions about line contains multiple characters

Iam new to java and I would like to make a question about java regular expression. 我是Java的新手,我想就Java正则表达式提出一个问题。

How can I check if a line contains only a specific string followed by any operator. 如何检查行是否仅包含特定字符串,后接任何运算符。 Also, and previous of the string does not contains "//". 另外,字符串的前一个不包含“ //”。

For example, if line is: 例如,如果line是:

//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 

Thanks in advance. 提前致谢。

You can use this negative lookahead based regex: 您可以使用以下基于负前瞻的正则表达式:

^(?:(?!//).)*\bx\b.*

In Java use: 在Java中使用:

boolean valid = str.matches("^(?:(?!//).)*\\bx\\b");

RegEx Breakup: 正则表达式分解:

^              # 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

RegEx Demo 正则演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM