Java regex to check if a pattern exists

java, regex

Solution

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$");

Problem

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.

Original source