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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16599249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 12:22:08  来源:igfitidea点击:

Regex expression to check for string name with underscore in java

javaregex

提问by MindBrain

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

我是 Java 中正则表达式的新手。如何检查文件名是否具有以下格式update_9_0_27?它是这样的[0-9][\\_][0-9][\\_][0-100]吗?

采纳答案by Andrew Clark

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 \dwill match a single digit, and the {1,2}after the final \dmeans "match between one and two digits (inclusive)".

^$开始串锚,这样你就不会只匹配字符串的一部分。每个\d将匹配一个数字,{1,2}最后的后面\d表示“匹配一位和两位数字(包括)”。

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

回答by RichardTheKiwi

Are the digit positions fixed, i.e. 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。