简体   繁体   English

如何在Java中使用正则表达式检查字符串是否包含两个字母和数量可变的数字?

[英]How to check with a regex if a String contains two letters and a variable amount of digits in Java?

I have this very specific use case where I want to check if a String contains 2 lower case letters, concatenated by a variable number of digits and a "-abc". 我有一个非常特殊的用例,我想检查一个字符串是否包含2个小写字母,由可变数目的数字和“ -abc”连接。

The "-abc" part must not be variable and should always be "-abc". “ -abc”部分不能为变量,而应始终为“ -abc”。 So in the end only the number of digits can be variable. 因此,最后只有数字位数是可变的。

It can be like this : 可能是这样的:

ab123-abc AB123-ABC

or like this : 或像这样:

ab123456-abc AB123456-ABC

or even like this : 甚至像这样:

cd5678901234-abc cd5678901234-ABC

I have tried the following but it does not work : 我已经尝试了以下方法,但是它不起作用:

if (s.toLowerCase().matches("^([a-z]{2})(?=.*[0-9])-abc")) {
    return true;
}

You are close instead of (?=.*[0-9]) use \\d* to match zero or more digits or \\d+ to match one or more digits, so you can use this regex ^[az]{2}\\d*-abc 您是封闭的,而不是(?=.*[0-9])使用\\d*匹配零个或多个数字,或者使用\\d+匹配一个或多个数字,因此可以使用此正则表达式^[az]{2}\\d*-abc

if(s.toLowerCase().matches("^[a-z]{2}\\d*-abc")){
   return true;
}

check regex demo 检查正则表达式演示

You don't need to do the if statement. 您不需要执行if语句。 Just do: 做就是了:

s.toLowerCase().matches("^[a-z]{2}\d+-abc")

as it already returns true . 因为它已经返回true Notice my answer is different from the one above because it requires a digit between the letters and -abc . 请注意,我的答案与上述答案不同,因为它要求在字母和-abc之间输入一个数字。

The regex that you want to use is: 您要使用的正则表达式为:

 /^[a-z]{2}[0-9]+-abc$/i
                ^ 
               "+" means "at least 1"

This will match exactly two letters, at least one number, and a trailing -abc . 这将恰好匹配两个字母,至少一个数字,以及一个尾随的-abc

You can also use the Pattern class to create a single Regex object. 您也可以使用Pattern类创建单个Regex对象。 You can then use the Pattern.CASE_INSENSITIVE flag to ignore case. 然后,您可以使用Pattern.CASE_INSENSITIVE标志忽略大小写。

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

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