提取括号内文本的方法解析
提取括号内文本的方法解析
此方法已在实际项目中应用,此处仅作简要记录以备查阅。
private static String regex = "\\{([^}]*)\\}";//匹配大括号
private static String regexx = "\\(([^}]*)\\)";//匹配小括号
public static void main(String[] args) {
String dakuohao = "{a+b}={c+d}>{d}";
Pattern compile = Pattern.compile(regex);
Matcher matcher = compile.matcher(dakuohao);
while(matcher.find()){
String group = matcher.group();
System.out.print(group+";");
}
System.out.println();
String xiaokuohao = "(a+b)=(c+d)>(d)";
Pattern comp = Pattern.compile(regex);
Matcher mat = comp.matcher(dakuohao);
while(mat.find()){
String group = mat.group();
System.out.print(group+";");
}
}
用于匹配大括号与小括号的正则逻辑相似,仅转义字符有所差异,其他符号亦可灵活替换。
对于成对出现的对称符号,处理方式同样适用。

接下来探讨如何识别纯数字、小数或二者混合的数值格式。
针对整数的匹配规则 ^([0-9]{1,}[.][0-9]*)$

针对小数的匹配规则 ^([0-9]{1,}[.][0-9]*)$
在测试过程中参考了多篇博客,发现多数方案无法有效排除数字中夹杂的特殊符号。

处理小数与整数混合情况的正则表达式 (^[0-9]*$)|(^([0-9]{1,}[.][0-9]*)$)

补充说明:Java环境下利用正则提取小括号内部内容的具体实现。
public class Test {
public static List getMsg(String msg) {
List list = new ArrayList();
Pattern p = Pattern.compile("(\\()([0-9a-zA-Z\\.\\/\\=])*(\\))");
Matcher m = p.matcher(msg);
while (m.find()) {
list.add(m.group(0).substring(1, m.group().length() - 1));
}
return list;
}
public static void main(String[] args) throws Exception {
String msg = "mSurface=Surface(name=com.bbk.launcher2/com.bbk.launcher2.Launcher)";
List list = getMsg(msg);
System.out.println(list);
}
}
要点回顾
上述内容分享了Java中正则表达式提取括号内容及数字校验的实用技巧,希望能对读者有所帮助。如有任何疑问,欢迎留言交流,作者将及时回复。感谢大家对本站的支持!若觉得本文有用,欢迎转载,请注明出处,谢谢!