Pattern pattern = Pattern.compile("(\\S+)\\s+(.+?)\\s+(\\S+)");
Matcher matcher = pattern.matcher("IA HEART RATE 184");
So my question is why does the pattern above capture HEART RATE in group 2. Shouldn’t ‘.+’ match one or more characters including a space char so shouldn’t group 2 capture HEART because it is followed by a space and that should match (.+?)\s+ correct ? So why is it matching HEART RATE?
P.S. I was using matches()
You haven’t shown how you’re using
matcher, but I’m guessing that you’re using itsmatches()method when what you really want is itsfind()method.matches()needs to match the pattern against the entire string, and the only way to do that is for group 2 to beHEART RATE. (If group 2 were justHEART, then group 3 would beRATE, and there would be a trailing184not matched by anything in the pattern.) If you were usingfind(), then group 2 would just beHEART, because that’s the minimum substring necessary that would allow the pattern to match part of the string.You also may be misunderstanding what
+?means. It tries to match as little as possible, while still resulting in a match overall.(.+?)\s+is perfectly capable of matchingHEART RATE; it’s just that it will prefer to matchHEART, as long as that doesn’t prevent the rest of the pattern from matching.