简体   繁体   中英

how to add optional white space in regex in java

Apologies, if this is duplicate. I am matching a sql string using regex in java. In my query i may or may not have where clause.

I am using following regex

\bselect\b\s(.*)\s\bfrom\b\s(.+)\s(?:where)?\s(?:(.*))

which is working fine for

select a,b from tab1 where a=b

and not matching for

select a,b from tab1

if i added two additional spaces its matching. It is clear that it is due to two \\s that i have used. But, i want to make those optional as well.

Please help me. I could not understand the other posts on this topic in stackoverflow

将空格放在非捕获组中:

\bselect\b\s(.*)\s\bfrom\b\s(\w+)(?:\swhere\s(.*))?

Not answering the question directly, but using a regex here is the wrong choice. SQL is a grammar, so any regex you come up with that can manage all cases will rapidly become far too complex to manage.

You should look at Antlr , which will allow you to define the grammar and act on whatever bits of it you like from within Java. There's even a pre-built grammar for SQLite which will allow you to get started very quickly.

You don't need to check that a match is at the end of a word and that it is followed by a space. + will match at least one space, so that allows extra spaces to be matched. \\S matches non-space so that is preferable to . which will match spaces.

\bselect\s+(\S+)\s+from\s+(\S+)\s*(?:where\s+(\S+))?

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