python - 查找仅在末尾可选地包含特定字符的字符串

标签 python python-3.x regex

我想找到没有 字符的字符串,在字符串的末尾可以选择出现这个字符。

我搜索了一些提示,诸如此类,但没有解决我的问题。

^(?!\.)(?!.*\.$)(?!.*\.\.)[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)

我想将 res1res2 组合成一个正则表达式,字符串结果如 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/

相关文章:

python - 如何使用 ruamel.yaml 自动添加引用?

python - 排序化学元组和系数

python-3.x - 在网格中查找最大值的坐标

python - 无法加载 dynlib/dll (Pyinstaller)

python - 当用户使用 django all-auth 注册时如何创建新的模型对象?

python - fork 后正在运行的线程会发生什么情况?

python - 如何为 Windows 构建 SQL Cipher Python 绑定(bind)

javascript - 使用正则表达式在 jQuery 中将字符添加到字符串前面

Javascript 将括号中的内容括在引号中

java - XXYXX 的正则表达式