VictorCreator
VictorCreator

Reputation: 744

How to find the text between ( and )

I have a few strings which are like this:

text (255)
varchar (64)    
...

I want to find out the number between ( and ) and store that in a string. That is, obviously, store these lengths in strings. I have the rest of it figured out except for the regex parsing part. I'm having trouble figuring out the regex pattern.

How do I do this?

The sample code is going to look like this:

Matcher m = Pattern.compile("<I CANT FIGURE OUT WHAT COMES HERE>").matcher("text (255)");

Also, I'd like to know if there's a cheat sheet for regex parsing, from where one can directly pick up the regex patterns

Upvotes: 4

Views: 233

Answers (5)

p.s.w.g
p.s.w.g

Reputation: 148980

You can use this pattern to match any text between parentheses:

\(([^)]*)\)

Or this to match just numbers (with possible whitespace padding):

\(\s*(\d+)\s*\)

Of course, to use this in a string literal, you have to escape the \ characters:

Matcher m = Pattern.compile("\\(\\s*(\\d+)\\s*\\)")...

Upvotes: 5

Peter Lawrey
Peter Lawrey

Reputation: 533442

I would use a plain string match

String s = "text (255)";
int start = s.indexOf('(')+1;
int end = s.indexOf(')', start);
if (end < 0) {
    // not found
} else {
    int num = Integer.parseInt(s.substring(start, end));
}

You can use regex as sometimes this makes your code simpler, but that doesn't mean you should in all cases. I suspect this is one where a simple string indexOf and substring will not only be faster, and shorter but more importantly, easier to understand.

Upvotes: 13

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

Matcher m = Pattern.compile("\\((\\d+)\\)").matcher("text (255)");
if (m.find()) {
    int len = Integer.parseInt (m.group(1));
    System.out.println (len);
}

Upvotes: 2

Ankit
Ankit

Reputation: 6622

int index1  = string.indexOf("(")
int index2  = string.indexOf(")")

String intValue = string.substring(index1+1, index2-1);

Upvotes: 2

Christian Stewart
Christian Stewart

Reputation: 15519

Here is some example code:

import java.util.regex.*;

class Main
{
  public static void main(String[] args)
  {
    String txt="varchar (64)";

    String re1=".*?";   // Non-greedy match on filler
    String re2="\\((\\d+)\\)";  // Round Braces 1

    Pattern p = Pattern.compile(re1+re2,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher m = p.matcher(txt);
    if (m.find())
    {
        String rbraces1=m.group(1);
        System.out.print("("+rbraces1.toString()+")"+"\n");
    }
  }
}

This will print out any (int) it finds in the input string, txt.

The regex is \((\d+)\) to match any numbers between ()

Upvotes: 2

Related Questions