我是一名Java开发人员,我是Regex的新手,我遇到类似here in Stackoverflow的问题。我有2个问题,
如果我有一个字符串,
It is very nice in summer and in summer time we swim, run, tan
它应该基于正面观察提取,"夏天我们"它应该提取,[smim,run,tan]作为数组。
我被困在这里,请帮助。
答案 0 :(得分:0)
在Java中,正则表达式本身不能返回数组。
但是,这个正则表达式将使用find()
循环返回您想要的值:
(?<=summer time we |\G(?<!^), )\w+
它与您提到的second answer几乎完全相同。
在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));