多种语言名称的正则表达式

Regex for names in multiple languages

我希望我的聊天机器人的用户在文本框中写下他的名字。

以下类型可以:

这是不正确的:

这是我试过的:

import re

value='John'

if not re.search(r'\d', value) and not re.search(r"[^a-zA-Z.\-\sÜüßäÄöÖ]", value) and not re.search(r"[.-]\Z", value):
  print('name is correct')
else:
  print('name is not correct')

我建议使用

re.search(r'^[^\W\d_]+(?:-[^\W\d_]+)*\.?$', text)

regex demo。如果最后还允许 -,则使用

re.search(r'^[^\W\d_]+(?:-[^\W\d_]+)*[.-]?$', text)

看到这个 regex demo。请注意,您可以使用 re.fullmatch 来确保完整的字符串匹配,然后您不需要锚点:re.fullmatch(r'[^\W\d_]+(?:-[^\W\d_]+)*[.-]?', text).

详情

  • ^ - 字符串开头
  • [^\W\d_]+ - 1+ Unicode 字母
  • (?:-[^\W\d_]+)* - - 和 1+ Unicode 字母
  • 的 0 次或多次重复
  • [.-]? - 可选的 -.
  • $ - 字符串结尾。