简体   繁体   English

用于在java中检查带下划线的字符串名称的正则表达式

[英]Regex expression to check for string name with underscore in java

I am new to regex expressions in java. 我是java中的正则表达式的新手。 How do I check if the file name has the following format update_9_0_27 ? 如何检查文件名是否具有以下格式update_9_0_27 Is it something like [0-9][\\\\_][0-9][\\\\_][0-100] ? 它是[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)". 每个\\d将匹配一个数字,而最终\\d之后的{1,2}意味着“匹配一个和两个数字(包括)”。

If the update portion of the file name is always constant, then you should use the following: 如果文件名的update部分始终是常量,那么您应该使用以下内容:

^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}$" . 请注意,在Java字符串中创建此正则表达式时,您需要转义每个反斜杠,因此该字符串将类似于"^update_\\\\d_\\\\d_\\\\d{1,2}$"

Are the digit positions fixed, ie 1-1-2? 数字位置是否固定,即1-1-2?

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

Used in a Java string, you'd need to escape the backslashes 在Java字符串中使用时,您需要转义反斜杠

"^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][\\\\_][0-100]您的意思是单位数,下划线,单位数,下划线,零到一百,以及这个序列可以出现在字符串中的任何地方

".*[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. 最后一部分专门测试0-100。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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