“ASSOC123″的Java正则表达式验证

huangapple go评论67阅读模式
英文:

Regex Validation for "ASSOC123" in Java

问题

我有一个任务,需要检查一个以大写的 "ASSOC" 开头,后面跟着3位数字的ID。我是Java方面的新手,还在学习正则表达式,所以任何帮助都将受之以欢迎!

英文:

I have a task to check an ID that must start with "ASSOC" in uppercase followed by 3 digits. I am a newbie in Java and still learning regex so any help would be welcome!

答案1

得分: 0

以下正则表达式匹配任何与所需模式匹配的字符串:ASSOC[0-9]{3}

如果您还想从匹配中提取三位数字ID,作为所谓的正则表达式组,表达式必须如下所示:ASSOC([0-9]{3})

[0-9] 在这里表示我们期望一个数字字符(数字)从0到9。花括号还表示正好3个数字,因此期望一个三位数。

在Regex101上,您还可以使用此正则表达式验证不同的输入。此外,详细解释了正则表达式。

  • 示例1:https://regex101.com/r/zEN9Gt/1
  • 示例2:https://regex101.com/r/zEN9Gt/2

在Java中,您可以按以下方式测试这个正则表达式:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "ASSOC([0-9]{3})";
final Pattern pattern = Pattern.compile(regex);

final Matcher matcher1 = pattern.matcher("ASSOC123");
final Matcher matcher2 = pattern.matcher("Assoc123");

if(matcher1.find()) {
  System.out.println(matcher1.group(1));
  // 由于"ASSOC123"是正则表达式的有效输入,
  // matcher1.find() 为true,我们可以输出三位数(注意:是第1组!)。
  // 第0组将是找到的整个表达式,因此是"ASSOC123"。
}
if(matcher2.find()) {
  // 由于"Assoc123"不匹配正则表达式,matcher2.find() 为false
}
英文:

The following regular expression matches any string that matches the pattern you want: ASSOC[0-9]{3}.

If you also want to extract the 3-digit ID as a so-called regex-group from the match, the expression must be as follows: ASSOC([0-9]{3}).

The [0-9] says here, that we expect a number-character (digit) of 0-9. The curly brackets also express that exactly 3 digits, therefore a 3-digit number is expected.

On Regex101 you also have the possibility to validate different inputs with this regex. Furthermore the regular expression is explained in detail.

In Java you could test this as follows:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "ASSOC([0-9]{3})";
final Pattern pattern = Pattern.compile(regex);

final Matcher matcher1 = pattern.matcher("ASSOC123");
final Matcher matcher2 = pattern.matcher("Assoc123");

if(matcher1.find()) {
  System.out.println(matcher1.group(1));
  // Since ASSOC123 is a valid input for the regular expression,
  // matcher1.find() is true and we can output the 3 digit number (attention: group 1!).
  // Group 0 would be the entire expression found, hence "ASSOC123".
}
if(matcher2.find()) {
  // Since "Assoc123" does not match the regular expression, matcher2.find() is false
}

huangapple
  • 本文由 发表于 2020年9月1日 17:36:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63685109.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定