[英]Want to extract the alphanumeric text with certain special characters using python regex
[英]want to include specific characters in regex using python
我试图从用户那里获取输入,并希望编译由每个字符组成的regex,我尝试使用list并将list用作失败的参数。
我不想匹配完整的字符串,但只希望单个字符更具体
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)
但这失败了!!!!
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
是一个列表,并且re.compile()
需要一个字符串。 变量名i
通常仅用于整数,而ch
例如用于字符(如果要使用简短的变量名,则应遵循约定:-)
也许像这样:
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))
或等同,但更短:
usertext = raw_input("Enter string of length 7 to generate your scrabble helper: ")
scrabble_re = re.compile(usertext)
?
我不确定我是否完全了解您的需求,但是也许这样会有所帮助:
x = raw_input("Enter string of length 7 to generate your scrabble helper: ")
p = re.compile('|'.join((c for c in x)))
这应该匹配输入字符串中的每个字符,而不是整个字符串。 您应该确保用户输入中没有特殊字符,但这是另一个问题。
听起来您更想发现两个字符串之间的字符重叠:
x = raw_input('enter string')
y = 'aeiou'
overlap = list(set(x) & set(y))
print(overlap)
这将打印x
和y
之间共享的字符。 我不完全理解您要做什么,但是正则表达式是高级编程中最常使用的一些东西,只有在确实需要它们时才应使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.