1

I'm trying to validate a these 2 simple sql queries

String sql1 = "select * from table".toLowerCase();
String sql2 = "select value from table".toLowerCase();

using this pattern

String pattern = "(select)(\\s)([\\*|\\w+])(\\s)(from)(\\s\\w+)";

then I print the value

System.out.println(sql1.matches(pattern)); // true
System.out.println(sql2.matches(pattern)); // false

the first one is ok, but I'm getting false in the second statement. Can someone help?

3 Answers 3

2

It's because of that you have putted the star character and word character modifier inside a character class.

When you want to choose between 2 separate word you shouldn't use character class for both.Instead you can use an logical OR (|) and a capture group,like following:

(\\*|\\w+)

Also note that when you put the | or + inside the character class your regex engine will escape them.

In addition if you want to match the whole of sentence you don't need to put all the words within a capture group.You can use anchors ^ and $ for specifying the start and end of the string:

"^select\\s(?:\\*|\\w+)\\sfrom\\s\\w+$"

(?:) is a none capturing group.

Read more about regular expressions http://www.regular-expressions.info/

Sign up to request clarification or add additional context in comments.

1 Comment

thanks so much, problem solved also thanks for the tutorial :)
2

You introduced square brackets in a group, the following line:

String pattern = "(select)(\\s)([\\*|\\w+])(\\s)(from)(\\s\\w+)";

Should be:

String pattern = "(select)(\\s)(\\*|\\w+)(\\s)(from)(\\s\\w+)";

Inside the square brackets + and | are considered as literal characters:

[\\*|\\w+] means a single character that is *, |, + or a letter.

Comments

0

I think the problem is because the + in regex is greedy, so the \w+ is consuming all the words. so it's consuming "value" "from" and "table". You can make it "lazy" by putting question mark after '+', like:

([\\*|\\w+?])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.