jamie
jamie

Reputation: 89

How do I capture values from a regex?

How do extract values from a regex where any placeholder can be rederenced by a $number_of_occurance value?

For example, I have a string final_0.25Seg1-Frag1 and I want to find all matches of this string in a file with 0.25 as a wildcard, which I can do using

Pattern regex = Pattern.compile( "/vod/final_\\d+\\.\\d+Seg1-Frag1" );
Matcher regexMatcher = regex.matcher(data2[0]);

I want to retain the value of the value in \\d+\\.\\d and find which among all the matched lines has the biggest value in this position.

Upvotes: 0

Views: 176

Answers (2)

Brian Agnew
Brian Agnew

Reputation: 272417

Have you looked at Pattern groups ? You can iterate through these to identify matched subexpressions.

From the linked example. Matcher.group(0) is the complete expression.

CharSequence inputStr = "abbabcd"; // could be a String type
String patternStr = "(a(b*))+(c*)";

// Compile and use regular expression
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.find();

if (matchFound) {
    // Get all groups for this match
    for (int i=0; i<=matcher.groupCount(); i++) {
        String groupStr = matcher.group(i);
    }
}

Upvotes: 2

Piotr Gwiazda
Piotr Gwiazda

Reputation: 12222

Please give an example. I guess you need to read Mathcer docs http://docs.oracle.com/javase/7/docs/api/index.html?java/util/regex/Matcher.html. You can access capturing groups via group method.

Upvotes: 0

Related Questions