Reputation: 11
I am trying to split a string in Java.
For example
Hello (1234)
The part after ( must not be included in the string. I am expecting the following:
Hello
How would you do it?
Upvotes: 0
Views: 96
Reputation: 375
You may try the following regex
String[] split = "Hello (1234)".split("\\s*\\([\\d]*\\)*");
System.out.println(split[0]);
\\s* space may be ignored
\\( ( or left parenthesis has special meaning in regex so \\( means only (
Same is the case with ) or right parenthesis \\)
\\d* digits may be present
You may use + instead of * if that character is present at-least once
Upvotes: 0
Reputation: 174706
Just split according to
(
character.Then get the value from index 0 of splitted parts.
"Hello (1234)".split("\\s*\\(")[0];
or
"Hello (1234)".split("\\s+")[0];
Upvotes: 3
Reputation: 17548
You can replace the contents in the parenthesis by nothing.
String str = "Hello(1234)";
String result = str.replaceAll("\\(.*\\)", "");
System.out.println(result);
You mention split operation in the question, but you say
The part after ( must not be included in the string. I am expecting the following:
So I'm assuming you are discarding the (1234)
? If you need to save it, consider the other answer (using split
)
Upvotes: 2