Home > Blockchain >  regex for capturing a group
regex for capturing a group

Time:07-22

I am learning regex for a project. Trying to find a regex that will capture (([[X]] 2)) in "\[format((([[X]] 2)),"#####0.######")]". Code that I am trying is here:

    Pattern patternFormat1 = Pattern.compile("\\[format\\(^(. ?),");
    String min = "\\[format((([[X]] 2)),\"#####0.######\")]";
    Matcher matcherMin = patternFormat1.matcher(min);
    if(matcherMin.find())
    System.out.println(matcherMin.group(1));

CodePudding user response:

If you simply want your regex to capture precisely (([[X]] 2)) and only that very string, the following regex will do the job:

\((\(.*\)\))

If you want to capture anything that looks like your pattern but has for example another number instead of the 2, you can use that one:

\((\(\(.*\ \d \)\))

Let me explain this last regex:

We are using 5 different things in this regex:

  1. Capturing groups ()
  2. Any character .
  3. Number character \d
  4. One or more time
  5. As much as you can (from 0 to inf) also called "greedy" *

So now let's break your goal in 5 parts:

  1. At least one number preceeded by a
  2. Preceeded by something
  3. Between 2 sets of parenthesis
  4. Capture the corresponding 3 steps
  5. Place me at the start of the three opening parenthesis

Theses parts corresponds to:

  1. \ \d
  2. .*\ \d
  3. \(\(.*\ \d \)\)
  4. (\(\(.*\ \d \)\))
  5. \((\(\(.*\ \d \)\))
  • You did it ;)

Note: This regex is far from being optimal. And this answer focuses on explaining regexes in your context, it may not work for all of your data if you have more, but you should be able to find the answer by yourself next time ;)
I recommend using https://regex101.com/ for regexes it's a very useful website.

CodePudding user response:

I found the answer. I made a small change and it worked.

Pattern.compile("\\[format\\((. ?),"); 

instead of

Pattern.compile("\\[format\\(^(. ?),")
  • Related