我一直在解决这个问题,包括尝试使用正则表达式之外的东西,我需要两个与此匹配的正则表达式
'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中对其进行修改或更改。您可以减小边界,例如可以大大简化此表达式。
RegEx电路
jex.im还有助于可视化表达式。
关于java - 复杂模式匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56239755/