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,349
  • 16
  • 58
  • 97
mkUltra
  • 2,562
  • 21
  • 42

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
  • 67,942
  • 4
  • 86
  • 123
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
  • 11,591
  • 2
  • 23
  • 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,371
  • 1
  • 28
  • 43