0

I'm been programming Java for a long time and recently I've started Python but there's something I can't figure out

import re

test_string = "1989 1989"
matched = re.match("\\d+", test_string)
print(bool(matched))

I'm expecting it to return false, however it returns true. basically I'm just looking for the counterpart of String.matches() in java... I thought maybe you could help me out! thank you in advance

4
  • Turn your regex string into raw string by putting a r before it. r"\\d+" and it will work as you expected. Commented Jul 4, 2020 at 10:20
  • 1
    @Asocia No, '\\d+' is entirely correct; using raw strings, which is a good recommendation, would mean using r'\d+', not r'\\d+'. But that won’t solve OP’s problem. Commented Jul 4, 2020 at 10:25
  • @KonradRudolph The OP says I'm expecting it to return false, however it returns true. So I thought they are expecting false because the test string doesn't contain "\" symbol but the regex searches for "\" symbol. Currently the regex just searches for a number, and putting r before string will make it search for "\" symbol also, hence will return false. Commented Jul 4, 2020 at 10:34
  • And I don't know java so I have no idea what String.matches() does if the actual question is that. Commented Jul 4, 2020 at 10:41

1 Answer 1

1

re.match matches if any prefix of the string matches the pattern. You probably want re.fullmatch, which checks whether the entire string matches the pattern.

Sign up to request clarification or add additional context in comments.

2 Comments

There is no way this answer solved the O.P.'s problem since the pattern does not include whitespace. The re.fullmatch function simply anchors the pattern at both ends of the string being matched.
@KurtisRader The OP wanted the pattern not to match their example string, but it did match, precisely because it was not anchored at the ends.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.