gpt4 book ai didi

java - 在 Java 中使用正则表达式

转载 作者:行者123 更新时间:2023-11-29 06:34:20 25 4
gpt4 key购买 nike

我在函数中检查字符串的优先级。有没有办法更改我的代码以合并正则表达式——我对正则表达式很不熟悉,虽然我已经在线阅读了一些教程,但仍然不太了解它。因此,我们将不胜感激任何指导。

例如,在字符串 XLYZ 中,如果 X 之后的字符不是 L 或 C,则会打印“violation”语句。下面是代码:

if (subtnString[cnt]=='X' && cnt+1<subtnString.length){
if(subtnString[cnt+1]!= 'L' || subtnString[cnt+1]!= 'C'){
System.out.println("Violation: X can be subtracted from L and C only");
return false;
}
}

有什么方法可以使用正则表达式替换这段代码吗?

最佳答案

你可以这样使用:

Pattern regex = Pattern.compile("^X[LC]");
Matcher regexMatcher = regex.matcher(subjectString);
if(regexMatcher.find() ) { // it matched!
}
else { // nasty message
}

the demo , 查看匹配的字符串。

解释

  • ^ anchor 断言我们在字符串的开头
  • X 匹配文字 X
  • [LC] 是匹配一个 L 或一个 C
  • 的字符类

引用

关于java - 在 Java 中使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24473835/

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