1
import re as regex
pattern = regex.compile(r'\w[\w\/\\-]*(\s*[\w\/\\-])*')
print pattern.findall("HELLO-WORLD")

This just prints out ['']

The regex works correctly on an online regex tester. Why is it not matching?

3
  • If I would put my regex \w[\w\/\\-]*(\s*[\w\/\\-])* on regex101.com it works fine and matches HELLO-WORLD as expected. Commented Jun 8, 2016 at 20:09
  • Try \w[\w/\\-]*(?:\s*[\w/\\-])*. See ideone.com/NIarL0 Commented Jun 8, 2016 at 20:11
  • @alexis: There is no lookahead in my suggested pattern, please see the answer. Commented Jun 8, 2016 at 20:17

1 Answer 1

1

You can use a non-capturing group (i.e. (?:\s*[\w/\\-]), the (?:...) does not form a capturing group and re.findall returns the whole match, not the captured group value(s)):

import re
pattern = re.compile(r'\w[\w/\\-]*(?:\s*[\w/\\-])*')
print(pattern.findall("HELLO-WORLD"))

See the IDEONE demo

Also, note that / symbol does not have to be escaped in a Python regex pattern.

Another point is that there is a PyPi regex module, and that is why I suggest using import re rather than hiding it with as regex.

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

3 Comments

This is perfect. Thank you.
Explanation: if re.findall contains capturing groups, it will only return the content captured by the groups; not the whole match.
Yes, here is the relevant link: docs.python.org/2/library/re.html#re.findall

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.