java - 复杂模式匹配
问题描述
我一直在思考这个问题,包括尝试正则表达式之外的东西,我需要两个匹配这个的正则表达式
'Name in "{Name1, Name2}"' and 'Name in "(Name1, Name2)"'
更准确地说,它匹配“名称”和“名称 1、名称 2”,即名称、名称 1 和名称 2 的任何单词和空格组合。
这就是我所拥有的
'(\\b)(\\s)in(\\s)\\\"{.+?}\\\"'
解决方案
在这里,我们也许可以使用捕获组编写一个表达式来涵盖这两种情况。也许类似于这样:
([})])?([A-Z][a-z]+)?([0-9]+)?(,\s)?([({])?
测试
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "([\\})])?([A-Z][a-z]+)?([0-9]+)?(,\\s)?([(\\{])?";
final String string = "{Name1, Name2}\n"
+ "(Name1, Name2)";
final String subst = "\\2";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
演示
const regex = /([})])?([A-Z][a-z]+)?([0-9]+)?(,\s)?([({])?/gm;
const str = `{Name1, Name2}
(Name1, Name2)`;
const subst = `$2`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
正则表达式
如果不需要此表达式,可以在regex101.com中对其进行修改或更改。例如,您可以减少边界并大大简化此表达式。
正则表达式电路
jex.im还有助于将表达式可视化。
推荐阅读
- networking - 网线断开后释放dhcp分配的ip
- apache-spark - Spark.sql 在 pyspark 中与 Google BigQuery 一起使用
- python - 无法使用 tabula-py 捕获表数据
- sql-server - 带有 2 个表的 SQL Server GROUP BY
- ios - Swift - 如何在 ViewController 上的“viewWillDisappear”时操作笔尖中的插座?
- powerbi - 如何创建基于 id 过滤掉代码的 power bi 度量
- r - Rshiny:在数据表中,我应该如何突出显示某些文本?
- java - 使用充气城堡库生成 PGP 密钥
- notepad++ - 重新组织编号顺序
- python - Python - 根据未知文本和已知字符获取子字符串(来自解析的 xml)