1

I can do it like this:

String s = "dsad.dd.ada....png";
int i = s.lastIndexOf('.');
String[] arr = {s.substring(0, i), s.substring(i + 1)};
System.out.println(Arrays.toString(arr));

Output:

[dsad.dd.ada..., png]

But i wanna understand how can i make it with regex.

String s = "dsad.dd.ada....png";
String[] arr = s.split("REGEX");
System.out.println(Arrays.toString(arr));
keyser
  • 18,829
  • 16
  • 59
  • 101
mkUltra
  • 2,828
  • 1
  • 22
  • 47

3 Answers3

4

You can use a lookahead assertion. (?= ... ) is a zero-width assertion which does not "consume" any characters on the string, but only asserts whether a match is possible or not.

The below regular expression first matches a literal dot then uses lookahead to assert what follows is any character except a dot "zero or more" times, followed by the end of the string.

String s = "dsad.dd.ada....png";
String[] arr = s.split("\\.(?=[^.]*$)");
System.out.println(Arrays.toString(arr)); //=> [dsad.dd.ada..., png]
hwnd
  • 69,796
  • 4
  • 95
  • 132
2

Use a lookahead to check for last .

"\\.(?=[^.]*$)"

At each . looks, if there's only characters, that are not . ahead until $ end. If so, matches .

Test at regex101.com; Regex FAQ

Community
  • 1
  • 1
Jonny 5
  • 12,171
  • 2
  • 25
  • 42
1

This one works for all split criteria you may come up with.

public static void main(final String[] args) {
    String test = "dsad.dd.ada....png";
    String breakOn = "\\.";
    String pattern = breakOn + "(?!.*" + breakOn + ".*)";
    System.out.println(Arrays.toString(test.split(pattern, 2)));
}

out: [dsad.dd.ada..., png]

ST-DDT
  • 2,615
  • 3
  • 30
  • 51