Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a Java String with '.'

Tags:

java

I have

1. This is a  test message

I want to print

This is a  test message

I am trying

String delimiter=".";
String[] parts = line.split(delimiter);
int gg=parts.length;

Than want to print array

 for (int k ;k <gg;K++)
    parts[k];

But my gg is always 0. am I missing anything. All I need is to remove the number and . and white spaces

The number can be 1 (or) 5 digit number

like image 472
The Learner Avatar asked Sep 27 '12 07:09

The Learner


People also ask

Can we split string with in Java?

You can use the split() method of java. lang. String class to split a string based on the dot. Unlike comma, colon, or whitespace, a dot is not a common delimiter to join String, and that's why beginner often struggles to split a String by dot.

What is split () in Java?

The split() method divides the string at the specified regex and returns an array of substrings.

How do you split a string with double quotes?

Use method String. split() It returns an array of String, splitted by the character you specified.

How do I split a string into multiple parts?

As the name suggests, a Java String Split() method is used to decompose or split the invoking Java String into parts and return the Array. Each part or item of an Array is delimited by the delimiters(“”, “ ”, \\) or regular expression that we have passed. The return type of Split is an Array of type Strings.


1 Answers

You are using "." as a delimiter, you should break the special meaning of the . char.

The . char in regex is "any character" so your split is just splitting according to "any character", which is obviously not what you are after.

Use "\\." as a delimiter

For more information on pre-defined character classes you can have a look at the tutorial.
For more information on regex on general (includes the above) you can try this tutorial


EDIT:
P.S. What you are up to (removing the number) can be achieved with a one-liner, using the String.replaceAll() method.

System.out.println(line.replaceAll("[0-9]+\\.\\s+", ""));

will provide output

This is a  test message

For your input example.

The idea is: [0-9] is any digit. - the + indicate there can be any number of them, which is greater then 0. The \\. is a dot (with breaking as mentioned above) and the \\s+ is at least one space.
It is all replaced with an empty string.

Note however, for strings like: "1. this is a 2. test" - it will provide "this is a test", and remove the "2. " as well, so think carefully if that is indeed what you are after.

like image 82
amit Avatar answered Sep 19 '22 11:09

amit