我想找到没有 。
字符的字符串,在字符串的末尾可以选择出现这个字符。
我搜索了一些提示,诸如此类,但没有解决我的问题。
^(?!\.)(?!.*\.$)(?!.*\.\.)[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)
我想将 res1
和 res2
组合成一个正则表达式,字符串结果如 False, True, True
。
最佳答案
你可以使用
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 demo . 详细信息:
^
- 字符串的开始[^。]*
- 除点以外的零个或多个字符。?
- 一个可选的点$
- 在字符串的末尾。
要使用此正则表达式从列表中获取有效字符串,您可以使用
rx = re.compile(r'^[^。]*。?$')
print( list(filter(rx.search, str_l)) )
# => ['aaa。', 'aaa']
关于python - 查找仅在末尾可选地包含特定字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72316753/