java - Spaces are not matched -
when run:
string line = " test"; pattern indentationpattern = pattern.compile("^[\\s]+"); matcher indentationmatcher = indentationpattern.matcher(line); if (indentationmatcher.matches()) { system.out.println("got match!"); int indent = indentationmatcher.group(0).length(); system.out.println("size of match: " + indent); } else { system.out.println("no match! :("); }
i no match. happening here? tested regex online @ http://www.regexplanet.com/advanced/java/index.html seems designed test regex in java.
changed few things, see comments:
string line = " test"; pattern indentationpattern = pattern.compile("^(\\s+)"); // changed regex matcher indentationmatcher = indentationpattern.matcher(line); if (indentationmatcher.find()) { // used find() instead of matches() system.out.println("got match!"); int indent = indentationmatcher.group(1).length(); // grouping 1 instead of 0 system.out.println("size of match: " + indent); } else { system.out.println("no match! :("); }
output:
got match! size of match: 2
reasons above changes:
find()
tries find pattern in input , gives true
when found. can used multiple times while (matcher.find()) { ... }
find matches input.
matches()
tries match finish input pattern , gives true
when finish input matches regex.
the whole pattern grouping 0, content of first capturing grouping ()
grouping 1. in case there's no difference, because outside of capturing group, there start of line ^
, has length/width of 0.
java regex space
No comments:
Post a Comment