2

Original String: "12312123;www.qwerty.com"

With this Model.getList().get(0).split(";")[1]

I get: "www.qwerty.com"

I tried doing this: Model.getList().get(0).split(";")[1].split(".")[1]

But it didnt work I get exception. How can I solve this?

I want only "qwerty"

IdontwearString
  • 265
  • 1
  • 19

6 Answers6

1

Try to use split(";|\\.") like this:

 for (String string : "12312123;www.qwerty.com".split(";|\\.")) {

        System.out.println(string);
    }

Output:

  12312123
  www
  qwerty
  com
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
1

Try this, to achieve "qwerty":

Model.getList().get(0).split(";")[1].split("\\.")[1]

You need escape dot symbol

Mirjalol Bahodirov
  • 2,053
  • 1
  • 11
  • 16
0

You can split a string which has multiple delimiters. Example below:

String abc = "11;xyz.test.com";
String[] tokens = abc.split(";|\\.");
System.out.println(tokens[tokens.length-2]);
Rupesh
  • 378
  • 7
  • 21
0

The array index 1 part doesn't make sense here. It will throw an ArrayIndexOutOfBounds Exception or something of the sort.

This is because splitting based on "." doesn't work the way you want it to. You would need to escape the period by putting "\." instead. You will find here that "." means something completely different.

Debosmit Ray
  • 5,228
  • 2
  • 27
  • 43
  • @IdontwearString Most of the answers here will work for your case. Please mark whichever one explains this best, so that people can get to the correct answer sooner, in the future. – Debosmit Ray Feb 01 '16 at 18:12
0

You'd need to escape the ., i.e. "\\.". Period is a special character in regular expressions, meaning "any character".

What your current split means is "split on any character"; this means that it splits the string into a number of empty strings, since there is nothing between consecutive occurrences of " any character".

There is a subtle gotcha in the behaviour of the String.split method, which is that it discards trailing empty strings from the token array (unless you pass a negative number as the second parameter).

Since your entire token array consists of empty strings, all of these are discarded, so the result of the split is a zero-length array - hence the exception when you try to access one of its element.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

Don't use split, use a regular expression (directly). It's safer, and faster.

String input = "12312123;www.qwerty.com";
String regex = "([^.;]+)\\.[^.;]+$";
Matcher m = Pattern.compile(regex).matcher(input);
if (m.find()) {
    System.out.println(m.group(1)); // prints: qwerty
}
Andreas
  • 154,647
  • 11
  • 152
  • 247