测试字符串是
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仅应在连接到单个主机的端口上启用。将集线器,集中器,交换机,网桥等连接到此\ n接口启用portfast时可能会导致临时桥接循环。\ 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句