Srinivasarao Daruna
Srinivasarao Daruna

Reputation: 3374

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

Upvotes: 0

Views: 443

Answers (3)

Neil Masson
Neil Masson

Reputation: 2689

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+))?

Upvotes: 0

user1596371
user1596371

Reputation:

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.

Upvotes: 1

Toto
Toto

Reputation: 91385

Put the spaces inside the non capturing groups:

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

Upvotes: 1

Related Questions