Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex expression to check for string name with underscore in java

Tags:

java

regex

I am new to regex expressions in java. How do I check if the file name has the following format update_9_0_27 ? Is it something like [0-9][\\_][0-9][\\_][0-100] ?

like image 697
MindBrain Avatar asked May 16 '13 23:05

MindBrain


People also ask

What is the regex for underscore?

The _ (underscore) character in the regular expression means that the zone name must have an underscore immediately following the alphanumeric string matched by the preceding brackets. The . (period) matches any character (a wildcard).

Is _ a special character in regex?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ).

How do you check if a string matches a regex in Java?

Variant 1: String matches() This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str. matches(regex) yields exactly the same result as the expression Pattern. matches(regex, str).

Can strings have Underscores?

Theoretically, an empty string also only consists of underscores; if that's undesirable you would need to also check whether strlen($str) is non-zero.


1 Answers

The following should work:

^[a-zA-Z]+_\d_\d_\d{1,2}$

The ^ and $ are beginning of string anchors so that you won't match only part of a string. Each \d will match a single digit, and the {1,2} after the final \d means "match between one and two digits (inclusive)".

If the update portion of the file name is always constant, then you should use the following:

^update_\d_\d_\d{1,2}$

Note that when creating this regex in a Java string you will need to escape each backslash, so the string will look something like "^update_\\d_\\d_\\d{1,2}$".

like image 123
Andrew Clark Avatar answered Oct 27 '22 15:10

Andrew Clark