我一直在思考这个问题,包括尝试正则表达式之外的东西,我需要两个与此匹配的正则表达式
'Name in "{Name1, Name2}"' and 'Name in "(Name1, Name2)"'
更准确地说,匹配“Name”和“Name1、Name2”,即“Name”、“Name1”和“Name2”是单词和空格的任意组合。
这就是我的
'(\\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也有助于形象化表达。
关于java - 复杂模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56239755/