0

I am a Java developer and I am new to Regex, I have similar problem as here in Stackoverflow . I have 2 issues,

  • SKIP does not work in Java
  • I started following the second approach as per this Regex link but my use case is as below,

if I have a string like,

It is very nice in summer and in summer time we swim, run, tan

It should extract based on Positive lookbehind, "summer time we", it should extract, [smim, run, tan] as an array.

I am stuck here, please help.

Krishna
  • 3
  • 2

1 Answers1

0

In Java, a regex cannot by itself return an array.

But, this regex will return the values you want using a find() loop:

(?<=summer time we |\G(?<!^), )\w+

It is almost identical to the second answer that you referred to.

In Java 9+, you can create array like this:

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));

Output

[swim, run, tan]

In Java 5+, you can do it with a find() loop:

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));
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • I have one more question `It is very nice in summer and in summer time we swim, run, tan, or walk, talk` is there a way to extract [swim, run, tan, walk, talk] . Thanks for your help. – Krishna May 30 '18 at 19:00
  • @Krishna Yes. Try **learning regex** and see if you can modify the regex above, instead of asking us to write your code for you. – Andreas May 30 '18 at 19:01