java - 带有逗号分隔列表的正向 Lookbehind
问题描述
我是一名 Java 开发人员,而且我是 Regex 的新手,我在 Stackoverflow 中遇到了类似的问题。我有2个问题,
- SKIP 在 Java 中不起作用
- 我开始按照这个正则表达式链接遵循第二种方法,但我的用例如下,
如果我有一个字符串,
It is very nice in summer and in summer time we swim, run, tan
它应该基于 Positive lookbehind 提取,“summer time we”,它应该提取 [smim, run, tan] 作为一个数组。
我被困在这里,请帮助。
解决方案
在 Java 中,正则表达式本身不能返回数组。
但是,这个正则表达式将使用find()
循环返回您想要的值:
(?<=summer time we |\G(?<!^), )\w+
它与您提到的第二个答案几乎相同。
在 Java 9+ 中,您可以像这样创建数组:
String s = "It is very nice in summer and in summer time we swim, run, tan";
String[] results = Pattern.compile("(?<=summer time we |\\G(?<!^), )\\w+")
.matcher(s).results().map(MatchResult::group)
.toArray(i -> new String[i]);
System.out.println(Arrays.toString(results));
输出
[swim, run, tan]
在 Java 5+ 中,您可以使用find()
循环来执行此操作:
String s = "It is very nice in summer and in summer time we swim, run, tan";
List<String> resultList = new ArrayList<String>();
Pattern regex = Pattern.compile("(?<=summer time we |\\G(?<!^), )\\w+");
for (Matcher m = regex.matcher(s); m.find(); )
resultList.add(m.group());
String[] results = resultList.toArray(new String[resultList.size()]);
System.out.println(Arrays.toString(results));
推荐阅读
- eclipse - MQTT 的数据包传送率比 CoAP 高多少?
- sql - 按地区名称(另一组)每组每种族的百分比
- java - 我想重复这个问题,但如果用户输入 -1 我希望程序停止?
- html - 我收到此错误:措辞错误:保留关键字“const”
- android - 为什么材质 FAB 在禁用时不改变颜色?
- javascript - 检查数组中的项目,如果在 JS/HTML 中有打印特定文本
- sql - 数据存在时内连接返回空集
- exception - Hive Exception CloseOperation Failed 的原因是什么:无序响应
- sql - 返回 2 个字符串的差异 SQL Server 2008
- c - fgets 使函数跳到代码的末尾,而不是正确运行 LOADS FILE AS NULL