[英]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. 我试图从用户那里获取输入,并希望编译由每个字符组成的regex,我尝试使用list并将list用作失败的参数。
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. a
是一个列表,并且re.compile()
需要一个字符串。 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 :-) 变量名
i
通常仅用于整数,而ch
例如用于字符(如果要使用简短的变量名,则应遵循约定:-)
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
. 这将打印
x
和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. 我不完全理解您要做什么,但是正则表达式是高级编程中最常使用的一些东西,只有在确实需要它们时才应使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.