首页 > 解决方案 > 复杂模式匹配

问题描述

我一直在思考这个问题,包括尝试正则表达式之外的东西,我需要两个匹配这个的正则表达式

'Name in "{Name1, Name2}"' and  'Name in "(Name1, Name2)"'

更准确地说,它匹配“名称”和“名称 1、名称 2”,即名称、名称 1 和名称 2 的任何单词和空格组合。

这就是我所拥有的

'(\\b)(\\s)in(\\s)\\\"{.+?}\\\"'

标签: javaregexregex-lookaroundsregex-groupregex-greedy

解决方案


在这里,我们也许可以使用捕获组编写一个表达式来涵盖这两种情况。也许类似于这样:

([})])?([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还有助于将表达式可视化。

在此处输入图像描述


推荐阅读