简体   繁体   中英

want to include specific characters in regex using python

I am trying to take input from the user and want to compile regex which consist of each character , I tried using list and using list as an argument which fails.

I dont want to match the complete string but only individual characters to be more specific

   x = raw_input("Enter string of length 7 to generate your scrabble helper: ")
    a = []
    for i in x:
        a.append(i)
    print(a)
    p = re.compile(a)

But this fails !!!!

Traceback (most recent call last):
  File "scrabb.py", line 8, in <module>
    p = re.compile(a)
  File "/usr/lib/python2.7/re.py", line 190, in compile
    return _compile(pattern, flags)
  File "/usr/lib/python2.7/re.py", line 232, in _compile
    p = _cache.get(cachekey)
TypeError: unhashable type: 'list'

a is a list, and re.compile() expects a string. The variable name i is usually only used for integers and eg ch is used for characters (if you're going to use short variable names you ought to stick to convention :-)

Perhaps something like:

usertext = raw_input("Enter string of length 7 to generate your scrabble helper: ")
lst = []
for ch in usertext:
    lst.append(ch)
print(lst)
scrabble_re = re.compile(''.join(lst))

or just the equivalent, but much shorter:

usertext = raw_input("Enter string of length 7 to generate your scrabble helper: ")
scrabble_re = re.compile(usertext)

?

I am not sure I understand exacly what you need, but maybe something like this would help:

x = raw_input("Enter string of length 7 to generate your scrabble helper: ")
p = re.compile('|'.join((c for c in x)))

This should match each character in input string, and not the whole string. You should make sure that there are no special character in user input, but that is other question.

It sounds like you're more interested in finding character overlap between two strings:

x = raw_input('enter string')
y = 'aeiou'

overlap = list(set(x) & set(y))

print(overlap)

This will print the characters that are shared between x and y . I don't totally understand what you are trying to do, but regex are some of the most abused things in higher level programming, you should only use them if you actually need them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM