Saturday 18 August 2018

java - Regex quantifiers and character classes

There are examples and descriptions of regex quantifiers in Java Tutorial.



Greedy - eats full string then back off by one character and try again




Regex: .*foo  // greedy 
String to search: xfooxxxxxxfoo
Found "xfooxxxxxxfoo"




Reluctant - start at the beginning then eat one character at a time




Regex: .*?foo  // reluctant quantifier
String to search: xfooxxxxxxfoo
Found "xfoo", "xxxxxxfoo"




Possessive - eats the whole string trying once for match




Regex: .*+foo // possessive quantifier
String to search: xfooxxxxxxfoo
No match found



They are ok and I understand them, but can someone explain to me what happens when regex is changed to the character class? Are there any other rules?





Regex: [fx]*
String to search: xfooxxxxxxfoo
Found "xf","","","xxxxxxf","","","",""

Regex: [fx]*?
String to search: xfooxxxxxxfoo
Found 15 zero-length matches


Regex: [fx]*+
String to search: xfooxxxxxxfoo
Found "xf","","","xxxxxxf","","","",""

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...