Lolly
Lolly

Reputation: 36432

Java regex to check if a pattern exists

I am trying to find whether a pattern exists in a string.

Pattern I want to check is:

String starting with space or "#",
then with specific string "value1" followed by space or tab,
then "value2" and again space or tab,
ends with "value3".


Here a sample string to check:

String str = "#  value1   values2 value3";

I tried the following regular expression, but it did't work:

str.matches("^\\s+#\\s+value1\\s+value2\\s+value3");

The above pattern always returns me false. Please help with regular expression. Any help will be really appreciated.

Upvotes: 3

Views: 3751

Answers (3)

RamValli
RamValli

Reputation: 4475

Try this regex (\s+|\s?#\s?).*value1.*(\s+|\t).*value2.*(\s+|\t).*value3.* It works even if you have whitespaces anywhere.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213311

Try this: -

str.matches("^[ #]value1\\s+value2\\s+value3$");

[ #] - matches a space or #

\\s+ - matches 1 or more spaces. So, it would match a space or tab

NOTE: - You have values2 instead of value2 in your string.

Also, your example string you posted, has both a space and a # at the starting. But you said the string starts with a space or a #. So, it will match your string, if you remove that space after the first #, or your # before your space, which is according to what you wrote.

If you want to match a space and a # at the starting of your string, as in your current String you posted. You need to use this regex: -

str.matches("^[ #]\\svalue1\\s+value2\\s+value3$");

Upvotes: 4

Well, I can tell you right now that that regex WILL fail for that input because it requires whitespace before the #

try

str.matches("^#?\\s+value1\\s+value2\\s+value3$");

that regex should match "# value1 value2 value3" or " value1 value2 value3" with variable amounts of whitespace

Upvotes: 1

Related Questions