ErEcTuS
ErEcTuS

Reputation: 867

Splitting string with parentheses

I have a list of String that follows this pattern:

'Name with space (field1_field2) CONST'

Example :

'flow gavage(ZAB_B2_COCUM) BS'    
'flowWithoutSpace (WitoutUnderscore) BS'

I would like to extract :

For the string inside the parentheses () I am using :

\(.*\)

Not sure about the other fields

Upvotes: 2

Views: 4375

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

You may use

String[] results = s.split("\\s*[()]\\s*");

See the regex demo

Pattern details

  • \\s* - 0+ whitespaces
  • [()] - a ) or (
  • \\s* - 0+ whitespaces

If your strings are always in the format specified (no parentheses, (...), no parentheses), you will have:

Name with space                      = results[0]
The values inside the brackets       = results[1]
The CONST value after the brackets   = results[2]

If you want a more controlled approach use a matching regex:

Pattern.compile("^([^()]*)\\(([^()]*)\\)(.*)$")

See the regex demo

If you use it with Matcher#matches(), you may omit ^ and $ since that method requires a full string match.

Java demo:

String regex = "^([^()]*)\\(([^()]*)\\)(.*)$";
String s = "flow gavage(ZAB_B2_COCUM) BS";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
if (matcher.matches()){
    System.out.println(matcher.group(1).trim()); 
    System.out.println(matcher.group(2).trim()); 
    System.out.println(matcher.group(3).trim()); 
} 

Here, the pattern means:

  • ^ - start of the string (implicit in .matches())
  • ([^()]*) - Capturing group 1: any 0+ chars other than ( and )
  • \\( - a (
  • ([^()]*) - Capturing group 2: any 0+ chars other than ( and )
  • \\) - a )
  • (.*) - Capturing group 3: any 0+ chars, as many as possible, up to the end of the line (use ([^()]*) if you need to restrict ( and ) in this part, too).
  • $ - end of string (implicit in .matches())

Upvotes: 4

Peter
Peter

Reputation: 198

This expression will generate 3 groups:

(.*?)(\(.*?\))\s*?(.*)

First group will match name, second one will match values inside brackets, third one will match the constant.

Upvotes: 1

nandal
nandal

Reputation: 2634

Use the following:-

String line = "'Name with space (field1_field2) CONST'";
Pattern pattern = Pattern.compile("([A-Za-z\\s]+)\\((.*)\\)(.*)\\'");
Matcher matcher = pattern.matcher(line);
String nameWithSpace = "";
String fieldsValuesInBrackets = "";
String constantValue = "";

if (matcher.find()) {
    nameWithSpace = matcher.group(1);
    fieldsValuesInBrackets = matcher.group(2);
    constantValue =  matcher.group(3);
}

Upvotes: 1

Related Questions