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.
Try this: –
[ #]– matches a space or #\\s+– matches 1 or more spaces. So, it would match a space or tabNOTE: – You have
values2instead ofvalue2in your string.Also, your example string you posted, has both a
spaceand a#at the starting. But you said the string starts with aspaceor 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
spaceand a#at the starting of your string, as in your currentStringyou posted. You need to use this regex: –