-1

i wrote a regular expression to match a string to be in range 0-255.

my regular expression is ([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])

i know my regular expression is technically incorrect as it will be true after matching the first character of the string matches [0-9] so even "1234" will be matched .

now i write it in python..

a="2514"
>>> if(re.match("([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",a)):
...     print("yes")

output = yes

but when i write it in java ..

String s="2514";
        if(s.matches("([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"))
        {
            System.out.println("yes");
        }

output is nothing

  • 1
    Because you have to read the docs and use the method that corresponds in function, not name. I had the same problem starting out with Python, but now I forgot the Java method names. – Mad Physicist Jun 11 '19 at 12:22
  • with ^ and $ added for defining what the beginning and ending must be it will not be different. your python code asks the question 'is there a match in this input given a regex'. your java code asks the question 'matches this input my regex?' so your examples are asking different questions, and as result the validation is different. (equivalent would be 'contains input a certain string vs. is input equal to certain string if we were just string searching instead of regex searching) – Joris D R. Jun 11 '19 at 12:26
  • `matches` requires a full string match in Java, while `re.match` in Python only anchors the match at the start of the string. – Wiktor Stribiżew Jun 11 '19 at 12:40

1 Answers1

1

From the docs of matches:

Attempts to match the entire region against the pattern.

This is similar to Python fullmatch().


find() is similar to Pythons match():

Attempts to find the next subsequence of the input sequence that matches the pattern.

jensgram
  • 31,109
  • 6
  • 81
  • 98
  • You were looking for `fullmatch`, I think – Mad Physicist Jun 11 '19 at 12:28
  • @MadPhysicist Yeah, I guess you're right. I was actually answering the question from the Java perspective pointing out that `match` ~ `find`, not `matches`. However, re-reading the question I realize that OP was probably looking for the Pythonic way of doing `matches`. I'll clarify. – jensgram Jun 11 '19 at 12:35