简体   繁体   中英

Regex expression to check for string name with underscore in java

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] ?

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}$" .

Are the digit positions fixed, ie 1-1-2?

^update\_\d\_\d\_\d\d$

Used in a Java string, you'd need to escape the backslashes

"^update\\_\\d\_\\d\\_\\d\\d$"

If by [0-9][\\\\_][0-9][\\\\_][0-100] you mean single-digit, underscore, single-digit, underscore, zero-to-one-hundred, and this sequence can appear anywhere in the string, then

".*[0-9][_][0-9][_](100|[1-9][0-9]|[0-9]).*"

Notice that I have now used [_] as an alternative to \\_ for specifying a literal underscore. The last part tests for 0-100 specifically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM