5

I need to find all two-char sumbols in UNICODE, except underscore. Current solutin is:

pattern = re.compile(ur'(?:\s*)(\w{2})(?:\s*)', re.UNICODE | re.MULTILINE | re.DOTALL)
print pattern.findall('a b c ab cd vs sd a a_ _r')
['ab', 'cd', 'vs', 'sd', 'a_', '_r']

I need to exclude underscore _ from regex, so a_ AND _r are not found. The problem is, my characters can be in any language. So i can't use regex like this: [^a-zA-Z]. For example, in russian:

print pattern.findall(u'ф_')

3 Answers 3

12

Exclude anything that's a non-word char AND _

[^\W_]

instead of

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

Comments

9

Your best bet would be to use the new regex module instead. One of it's features is that it can remove characters from a character set:

import regex as re

pattern = re.compile(ur'(?:\s*)([\w--_]{2})(?:\s*)', re.UNICODE | re.MULTILINE | re.DOTALL)

The [\w--_] syntax creates a character set that is the same as \w with the underscore character removed from the matching characters.

Comments

0

This seems to work for me:

a="Exclude_from_search"
re.search("(\w[^_]+)", a).group(0)
'Exclude'

Comments

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.