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
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.
The split() method divides the string at the specified regex and returns an array of substrings.
Use method String. split() It returns an array of String, splitted by the character you specified.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With