Tania
Tania

Reputation: 11

regex for capturing a group

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));

Upvotes: 1

Views: 103

Answers (3)

The fourth bird
The fourth bird

Reputation: 163577

The ^ asserts the start of the string which will not work in your pattern as it matches characters before that.

You can use the caret ^ but in the context of a negated character class matching any character except a comma.

\[format\(([^,]+),

Regex demo

In Java with the doubled backspaces:

String regex = "\\[format\\(([^,]+),";

Upvotes: 0

xonturis
xonturis

Reputation: 98

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.

Upvotes: 1

Tania
Tania

Reputation: 11

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

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

instead of

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

Upvotes: 0

Related Questions