java - 复杂模式匹配

标签 java regex regex-lookarounds regex-group regex-greedy

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

'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)?([({])? 

enter image description here

测试

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也有助于形象化表达。

enter image description here

关于java - 复杂模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56239755/

相关文章:

java - JPA DBUnit HsqlDb : Disable constraint checks?

java - 正则表达式捕获其间重复组数量未知的文本

Javascript 正则表达式 - 捕获前面有另一个字符串的字符串

java - 处理大量输入数据时出现 StackOverflow 错误

regex - 如何在没有积极前瞻的情况下重写正则表达式?

java - JDBM的headMap

java , Swing ;简单的 gui 在哪里创建对象

regex - Notepad++查找并用正则表达式替换

Java 正则表达式跳过匹配

Python re.sub 将部分字符串更改为 ascii