簡體   English   中英

想要使用python在正則表達式中包含特定字符

[英]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)

這將打印xy之間共享的字符。 我不完全理解您要做什么,但是正則表達式是高級編程中最常使用的一些東西,只有在確實需要它們時才應使用它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM