AlexanderH
AlexanderH

Reputation: 11

Split a string in Java containing (

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

Answers (3)

N3WOS
N3WOS

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

Avinash Raj
Avinash Raj

Reputation: 174706

Just split according to

  • zero or more spaces.
  • And the following ( character.
  • Then get the value from index 0 of splitted parts.

    "Hello (1234)".split("\\s*\\(")[0];
    

or

    "Hello (1234)".split("\\s+")[0];

Upvotes: 3

James Wierzba
James Wierzba

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

Related Questions