简体   繁体   中英

java Regular expressions about line contains multiple characters

Iam new to java and I would like to make a question about java regular expression.

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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