gpt4 book ai didi

java - 正则表达式前瞻和后视匹配

转载 作者:行者123 更新时间:2023-11-30 07:19:48 24 4
gpt4 key购买 nike

我需要获取一个字符串并提取模式的每个实例,并且只提取模式。

String test = "This is a test string to experience with regex by separing every instance of the word test and words that trail test";

所以现在该模式必须找到单词 test 以及它前后的任何不是 test 的单词。所以基本上它必须找到 3 个这种模式的实例。

我期望的 3 个结果如下:

  1. 这是一个测试字符串,用于通过分隔单词的每个实例来试验正则表达式
  2. 测试和跟踪的单词
  3. 测试

我在 gskinner 上尝试过正前瞻和负前瞻但还没有运气。

最佳答案

试试这个

(\s*\b(?!test\b)[a-z]+\b\s*)*test(\s*\b(?!test\b)[a-z]+\b\s*?)*

查看here on Regexr .

在 Java 中,我会将 [a-z] 替换为 \p{L},但 regexr 不支持 Unicode 属性。 \p{L}Unicode code point with the property letter , 这将匹配任何语言的每个字母。

解释:

(\s*\b(?!test\b)[a-z]+\b\s*)* 匹配一系列不是“test”的单词。这是由否定先行断言 (?!test\b) 确保的。

test 匹配“test”

最后还是一样:再次匹配一系列不是“test”的单词 (\s*\b(?!test\b)[a-z]+\b\s*? )*

关于java - 正则表达式前瞻和后视匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14397263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com