How to find text between (s)

I have a few lines that would look like this:

text (255) varchar (64) ... 

I want to find out the number between (and) and store this in a string. That is, obviously, keep these lengths in lines. I have everything that has been figured out, with the exception of regular expression parsing. I find it hard to understand the regex pattern.

How to do it?

Sample code will look like this:

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

In addition, I would like to know if there is a cheat sheet for regular analysis of regular expressions, from where you can directly select regular expression patterns

+4
source share
5 answers

I would use a simple 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 a regex, because sometimes it makes your code simpler, but that doesn't mean you should in all cases. I suspect this is one where a simple indexOf line and a substring will not only be faster, but also shorter, but more importantly, easier to understand.

+13
source

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

 \(([^)]*)\) 

Or this, to match only numbers (with possible filling in spaces):

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

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

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

Here is a sample 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 any (int) that it finds in the input string, txt .

The regular expression \((\d+)\) matches any numbers between ()

+2
source
 Matcher m = Pattern.compile("\\((\\d+)\\)").matcher("text (255)"); if (m.find()) { int len = Integer.parseInt (m.group(1)); System.out.println (len); } 
+2
source
 int index1 = string.indexOf("(") int index2 = string.indexOf(")") String intValue = string.substring(index1+1, index2-1); 
+2
source

Source: https://habr.com/ru/post/1494359/


All Articles