【问题标题】:Only accept alphanumeric characters and underscores for a string in pythonpython 中的字符串只接受字母数字字符和下划线
【发布时间】:2013-06-03 16:09:55
【问题描述】:

我目前正在为 ArcMap 10 (updateMessages) 中的工具参数编写验证代码,并且需要防止用户在字符串中使用非字母数字字符,因为它将用于命名要素类中新创建的字段。

到目前为止,我一直使用“str.isalnum()”,但这当然不包括下划线。有没有一种只接受字母数字字符和下划线的有效方法?

if self.params[3].altered:
  #Check if field name already exists
  if str(self.params[3].value) in [f.name for f in arcpy.ListFields(str(self.params[0].value))]:
    self.params[3].setErrorMessage("A field with this name already exists in the data set.")
  #Check for invalid characters
  elif not str(self.params[3].value).isalnum():
    self.params[3].setErrorMessage("There are invalid characters in the field name.")   
  else:
    self.params[3].clearMessage()

return

【问题讨论】:

    标签: python arcpy parameters field validation


    【解决方案1】:
    import re
    if re.match(r'^\w+$', text):
    

    【讨论】:

    • PEP8 — 一行中的一条语句 -> \npass :)
    • 谢谢!顺便说一句,这与花哨无关 -> 如果 StackOverflow 上的这些“示例”和“答案”代码将使用 “良好的代码格式”,那么我们会将这些约定传授给任何开始编程,或者不熟悉python。实际上,我们的工作会变得更轻松:阅读格式良好的代码总是一种乐趣。
    • @PeterVaro 当然,但也要注意 PEP-8 就像海盗的代码 “代码更像是您所说的指导方针而不是实际规则。”,我几乎完全遵循它,但有时我会注意到一行if 对代码有益的情况。在这种情况下,我认为您推广两行是正确的
    • @PaulKenjora 错了。 \w When the LOCALE and UNICODE flags are not specified, matches any alphanumeric character and the underscoredocs.python.org/2/library/re.html
    【解决方案2】:

    试试正则表达式:

    import re
    if re.match(r'^[A-Za-z0-9_]+$', text):
        # do stuff
    

    【讨论】:

    • 对,错过了 alpha 部分。 :)
    • re.match 从一开始就匹配,所以 ^ 是多余的
    • 我认为在正则表达式方面具体化是一种很好的做法。这样,表达式也是可移植的。
    • 那么你应该使用re.search
    【解决方案3】:

    如果您使用的是 Python3 并且您的字符串中有非 ASCII 字符,则最好使用 8 位字符串设置编译正则表达式。

    import sys
    import re
    
    if sys.version_info >= (3, 0):
        _w = re.compile("^\w+$", re.A)
    else:
        _w = re.compile("^\w+$")
    
    if re.match(_w, text):
        pass
    

    更多信息请参考here

    【讨论】:

      【解决方案4】:

      另一种方法,在这种特定情况下不使用正则表达式:

      if text.replace('_', '').isalnum():
         # do stuff
      

      您也可以只检查 ascii 字符:

      if text.replace('_', '').isalnum() and text.isascii():
         # do stuff
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-09
        • 1970-01-01
        • 2019-02-18
        • 1970-01-01
        • 1970-01-01
        • 2018-11-25
        • 2020-12-22
        • 1970-01-01
        相关资源
        最近更新 更多