-3

I tried the following regex:

sentences = sb.toString().split("(?<=[a-z])*\\.\\s*");

I am using a stringBuilder sb and converting it to string and then using a split function
The regex checks for 0 or more characters before '.' and 0 or more spaces after the '.'

However, it doesn't work for the following input

Hello World. Shipped to U.S on Friday.We are here .Good input 

But I need to keep the space before We are here

Req Output

Hello World
 Shipped to U.S on Friday
 We are here
Good input
17
  • 6
    why cant u jst split on the .
    – leoOrion
    Aug 8, 2020 at 18:42
  • 1
    Well, remove the \\s* part then?
    – 41686d6564
    Aug 8, 2020 at 18:46
  • 1
    @leoOrion I can only assume that the OP doesn't want to split on the dot in "15.05", for example.
    – 41686d6564
    Aug 8, 2020 at 18:47
  • 15.05?? uh?? what?
    – leoOrion
    Aug 8, 2020 at 18:49
  • @leoOrion Um, what's so weird about 15.05 (as an example)?
    – 41686d6564
    Aug 8, 2020 at 18:50

3 Answers 3

3

use this regex: ([^\.]+)(\.|$)*?
you can read about group matchers and see the full matches here : https://regex101.com/r/yV9GES/5

edit: updated the link for answer in the comment.

1
  • my bad! the closest i can come to match the OP's req is this regex: /([^\.]+)(\.|$)*?/ It does break for Shipped to U.S on Friday though.
    – Khushboo
    Aug 8, 2020 at 19:46
1

Split your string using \\. i.e. on .

Demo:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        System.out.println(Arrays.toString("Hello World. We are here .Good input.".split("\\.")));
    }
}

Output:

[Hello World,  We are here , Good input]
2
  • 1
    I think we need to add trim() for every generated statement. Aug 8, 2020 at 18:47
  • 1
    @hiteshbedre - No. OP wants to keep the space. Please check his expected output. Aug 8, 2020 at 18:48
1

Why do you have to use a RegEx?

You can simply use indexOf and substring

  public List<String> splitOnDot(String input) {
    List<String> result = new ArrayList<>();
    int idx;
    while ((idx = input.indexOf('.')) != -1) {
      result.add(input.substring(0, idx));
      input = input.substring(idx + 1);
    }
    return result;
  }

Successful test:

@Test
  public void test1() {
    assertThat(splitOnDot("Hello World. We are here .Good input.")).contains("Hello World", " We are here ", "Good input");
  }

Not the answer you're looking for? Browse other questions tagged or ask your own question.