Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the text between ( and )

Tags:

java

regex

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

like image 983
VictorCreator Avatar asked Nov 29 '22 08:11

VictorCreator


1 Answers

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.

like image 68
Peter Lawrey Avatar answered Dec 04 '22 16:12

Peter Lawrey