I’m not used to them and having trouble with the java syntax “matches”.
I have two files one is 111.123.399.555.xml the other one is Conf.xml.
Now I only want to get the first file with regular expressions.
string.matches("[1-9[xml[.]]]");
doesnt work.
How to do this?
The use of
string.matches("[1-9[xml[.]]]");will not work because[]will create a character class group, not a capturing group.What this means is that, to java, your expression is saying
"match any of: [1-to-9 [or x, or m, or l [or *any*]]]"(*any* here is because you did not escape the., and as it, it will createa match any charactercommand)Important:
“\” is recognized by java as a literal escape character, and for it to be sent to the matcher as an actual matcher’s escape character (also “\”, but in string form), it itself needs to be escaped, thus, when you mean to use “\” on the matcher, you must actually use “\\”.
This is a bit confusing when you are not used to it, but to sum it up, to send an actual “\” to be matched to the matcher, you might have to use “\\\\”! The first “\\” will become “\” to the matcher, thus a scape character, and the second “\\”, escaped by the first, will become the actual “\” string!
The correct pattern-string to match for a
###.###.###.###.xmlpattern where the “#” are always numbers, isstring.matches("(\\d{3}\\.){4}xml"), and how it works is as follows:\\d= will match a single digit character. It is the same asusing
[0-9], just simpler.{3}specifies matching for “exactly 3 times” for the previous\\d. Thus matching###.\\.matches a single dot character.()enclosing the previous code says “this is a capturing group”to the matcher. It is used by the next
{4}, thus creating a “matchthis whole
###.group exactly 4 times”, thus creating “match###.###.###.###.“.xmlbefore the pattern-string ends will matchexactly “xml”, which, along the previous items, makes the exact match for that pattern: “
###.###.###.###.xml“.For further learning, read Java’s Pattern docs.