我想找到其中沒有。字符的字串,在字串的末尾可以選擇出現這個字符。
我搜索了一些類似的提示,但沒有解決我的問題。
^(?!\.)(?!.*\.$)(?!.*\.\.)[a-zA-Z0-9_.] $
(?!\.) - don't allow . at start
(?!.*\.\.) - don't allow 2 consecutive dots
(?!.*\.$) - don't allow . at end
我試著用
str_l = ["aaa。bbb。","aaa。","aaa"]
for str1 in str_l:
res1 = re.search(r'(.*?!。*$)', str1) #if 。not in string, return True
res2 = re.search(r'(?<!(。)。$)',str1) # if 。 only appear at the end of string, return True, but not solved
print(res1,res2)
我想將res1and組合res2到一個正則運算式中,字串結果如False, True, True.
uj5u.com熱心網友回復:
您可以使用
import re
str_l = ["aaa。bbb。","aaa。","aaa"]
for str1 in str_l:
print(str1, '=>', bool(re.search(r'^[^。]*。?$', str1)))
輸出:
# => aaa。bbb。 => False
aaa。 => True
aaa => True
請參閱Python 演示。詳情:
^- 字串的開始[^。]*- 除點以外的零個或多個字符。?- 一個可選的點$- 在字串的末尾。
要使用此正則運算式從串列中獲取有效字串,您可以使用
rx = re.compile(r'^[^。]*。?$')
print( list(filter(rx.search, str_l)) )
# => ['aaa。', 'aaa']
uj5u.com熱心網友回復:
這可以通過以下代碼完成。
import re
p = re.compile("^(?:(?!。).)*(。$)?(?!.*。).*$")
l = [
"aaa。bbb。",
"aaa bbb。", # matches because only at end
"aaa。bbb",
"。aaa bbb",
"aaa bbb", # matches because none found
]
print([s for s in l if p.match(s)])
結果是:
['aaa bbb。', 'aaa bbb']
完整的解釋可以在 regex101.com上找到。
與更簡潔的匹配運算式相比,此匹配運算式的唯一優點^[^。]*。?$是除了給定字符之外,它還可以與字串一起使用。因此,假設您需要匹配可能以“foo”結尾的字串,但它不應出現在字串的前面。然后你可以使用^(?:(?!foo).)*(foo$)?(?!.*foo).*$.
但是,它慢了大約 60%。您可以在此處查看測驗和結果:
import re
import timeit
a = re.compile("^(?:(?!。).)*(。$)?(?!.*。).*$")
b = re.compile("^[^。]*。?$")
l = [
"aaa。bbb。",
"aaa bbb。", # matches because only at end
"aaa。bbb",
"。aaa bbb",
"aaa bbb", # matches because none found
]
print(
timeit.timeit(
"matches = [s for s in l if a.match(s)]",
setup="from __main__ import (l, a)",
)
)
print(
timeit.timeit(
"matches = [s for s in l if b.match(s)]",
setup="from __main__ import (l, b)",
)
)
這使:
2.6208932230000004
1.6510743480000003
uj5u.com熱心網友回復:
另一種方法可以拆分。
如果使用 split 并且 。字串末尾是 is,則串列中的最后一項將為空。
如果沒有出現,則串列大小為 1。
str_l = ["aaa。bbb。", "aaa。", "aaa", "。", "。 ", "。。"]
for str1 in str_l:
lst = str1.split(r"。")
nr = len(lst)
print(f"'{str1}' -> {nr == 1 or nr == 2 and lst[1] == ''}")
輸出
'aaa。bbb。' -> False
'aaa。' -> True
'aaa' -> True
'。' -> True
'。 ' -> False
'。。' -> False
查看Python 演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479795.html
