gpt4 book ai didi

java - 我可以在具有以下条件的 java 中为以下字符串获取适当的正则表达式吗

转载 作者:行者123 更新时间:2023-11-30 10:56:01 26 4
gpt4 key购买 nike

测试字符串是

It is a test data
%Warning: portfast should only be enabled on ports connected to a single
host. Connecting hubs, concentrators, switches, bridges, etc. to this
interface when portfast is enabled can cause temporary bridging loops.
Use with CAUTION
Test is a test.

如果字符串中有% 符号,则该字符串无效。但如果 % 后跟以下字符序列,则它是有效的,“%Warning: portfast should only be enabled on ports connected to a single\n host. Connecting hubs, concentrators, switches, bridges等在启用 portfast 时\n 到此接口(interface)可能会导致临时桥接循环。\n 请谨慎使用。即使在这种情况下,“%”符号也只能出现一次。

我的代码是:

public class Abc {

public static void main(String[] args) {
String reg="%(Warning: portfast should only be enabled on ports connected to a single\n host. Connecting hubs, concentrators, switches, bridges, etc. to this\n interface when portfast is enabled can cause temporary bridging loops.\n Use with CAUTION)([^%])";
String str = "%Warning: portfast should only be enabled on ports connected to a single\n host. Connecting hubs, concentrators, switches, bridges, etc. to this\n interface when portfast is enabled can cause temporary bridging loops.\n Use with CAUTIONTest is a testData is invalid%";
Pattern regEx2 = Pattern
.compile(reg);
Matcher matcher = regEx2.matcher(str);
if (matcher.find()) {
System.out.println("valid");
} else {
System.out.println("invalid");
}
}
}

但我没有得到预期的结果。我可以获得合适的正则表达式吗?

最佳答案

也许您可以将您的代码与另一个获取“%”计数的表达式组合在一起

 public static void main(String[] args) {
String reg = "%Warning: portfast should only be enabled on ports connected to a single\n host. Connecting hubs, concentrators, switches, bridges, etc. to this\n interface when portfast is enabled can cause temporary bridging loops.\n Use with CAUTION";
String str = "%Warning: portfast should only be enabled on ports connected to a single\n host. Connecting hubs, concentrators, switches, bridges, etc. to this\n interface when portfast is enabled can cause temporary bridging loops.\n Use with CAUTIONTest is a testData is invalid%";
Pattern regEx2 = Pattern.compile(reg);
Matcher matcher = regEx2.matcher(str);
int occurences = str.length() - str.replace("%", "").length();

if (matcher.find() && occurences <= 1) {
System.out.println("valid");
} else {
System.out.println("invalid");
}

}

如果您有 StringUtils 类,那么您可以使用它的方法 countMatches

关于java - 我可以在具有以下条件的 java 中为以下字符串获取适当的正则表达式吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33140824/

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