简体   繁体   中英

Java Regex Matching, 2 simple regex questions

Question 1.

String matchedKey = "sessions.0.something.else";
Pattern newP = Pattern.compile("sessions\\.([^\\.]+)(\\..+)");
m = newP.matcher(matchedKey);

System.out.println(m.group(1)); // has nothing. Why?

sessions\\. // word "sessions" followed by .
([^\\.]+)   // followed by something that is not a literal . at least once
(\\..+)     // followed by literal . and anything at least once

I would have expected for m.group(1) to be 0

Question 2

String mask = "sessions.{env}";
String maskRegex = mask.replace(".", "\\\\.").replace("env", "(.+)")
                                   .replace("{", "").replace("}", "");
// produces mask "sessions\\.(.+))"

When used as

Pattern newP = Pattern.compile("sessions\\.(.+))"); // matches  matchedKey (above)
Pattern newP = Pattern.compile(maskRegex);          // does not match matchedKey (above)

Why is that?

You haven't called Matcher.find() OR Matcher.macthes() method in your both questions.

Use it like this:

if (m.find())
   System.out.println("g1=" + m.group(1));

Also good to check Matcher.groupCount() value.

before you can access the groups of a matcher, you have to call matches on it:

String matchedKey = "sessions.0.something.else";
Pattern newP = Pattern.compile("sessions\\.([^\\.]+)(\\..+)");
m = newP.matcher(matchedKey);
if (m.matches()) {
    System.out.println(m.group(1));
}

find will also do if you want to find the pattern anywhere within the string. matches checks if the whole string matches your pattern from the beginning to the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM