gpt4 book ai didi

Java USSD 代码正则表达式模式

转载 作者:行者123 更新时间:2023-11-29 04:20:30 24 4
gpt4 key购买 nike

如何测试字符串是否为有效的 ussd 代码?我试图编写自己的正则表达式但失败了。

它应该以 * 符号开头,后跟任何整数或另一个 *。星号不能重复。它不能**。最后一个符号必须是#。此符号也允许使用一次。

我的测试:

public static final Pattern USSD = Pattern.compile("Pattern here");

System.out.println(USSD.matcher("*123#").matches()); // Must be true
System.out.println(USSD.matcher("*1*2*3#").matches()); // Must be true
System.out.println(USSD.matcher("*1#23#").matches()); // Must be false
System.out.println(USSD.matcher("***123###").matches()); // Must be false
System.out.println(USSD.matcher("*12**3#").matches()); // Must be false

我已经尝试过的:

  • This answer不是我要找的。它允许双重 * 和双重 #
  • ^\*([0-9]|\*?)*#$ 对双星没有帮助

最佳答案

您可以将以下正则表达式与 matches() 一起使用:

(?:\*\d+)+#

参见 regex demo .

在Java中,声明为

String pattern = "(?:\\*\\d+)+#";

图案细节

  • ^ -(隐含在 matches() 中)- 字符串的开头
  • (?:\*\d+)+ - 模式序列出现 1 次或多次:
    • \* - * 字符
    • \d+ - 1+ 位
  • $ -(隐含在 matches() 中)- 字符串结尾。

Java demo :

List<String> strs = Arrays.asList("*123#","*1*2*3#","*1#23#","***123###","*12**3#");
Pattern pat = Pattern.compile("(?:\\*\\d+)+#");
for (String str : strs) {
System.out.println(str + ": " + pat.matcher(str).matches());
}

输出:

*123#: true
*1*2*3#: true
*1#23#: false
***123###: false
*12**3#: false

关于Java USSD 代码正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49545374/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com