正则表达式分隔字符串和正则表达式列表

时间:2015-05-08 09:38:06

标签: python regex regex-negation

我有包含字符串和正则表达式的python输入列表。

str_regex = ['normal_string_1', ''^(?![_\-])[A-Za-z0-9\-_]+$', 'normal_string_2'] 

我需要将此列表分隔为字符串列表和正则表达式列表。 总之,下面是输入和所需的输出。

输入:

['normal_string_1', ''^(?![_\-])[A-Za-z0-9\-_]+$', 'normal_string_2']

输出:

['normal_string_1', 'normal_string_2'], ['^(?![_\-])[A-Za-z0-9\-_]+$']

我打算组建一个正则表达式来做到这一点。类似“应仅包含[A-Z][a-z]”之类的内容。这是最好的方法吗?

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,您希望将字符串传递给函数以及不同正则表达式列表,并返回匹配的正则表达式。这应该可以解决问题:

import re
def contains(string, regexes):
  lst = []
  for regex in regexes:
    match = re.findall(regex, string)
    if len(match) > 0 and len(match[0]) == len(string):
      return string + " contains only \"" + regex + "\""
  return "No matching regex was found"

if __name__ == "__main__":
  regexes = [
    "[a-z]+",     # lower case
    "[A-Z]+",     # upper case
    "[a-zA-Z]+",  # mixed case
    "\d+",        # digits
    "[a-z\d]+",   # digits and lower case
    "[A-Z\d]+",   # digits and upper case
    "[a-zA-Z\d]+" # digits and mixed case
  ]
  print contains("SHOULD" , regexes)
  print contains("should" , regexes)
  print contains("Should" , regexes)
  print contains("123"    , regexes)
  print contains("123as"  , regexes)
  print contains("123AS"  , regexes)
  print contains("123aS"  , regexes)

以上打印

SHOULD contains only "[A-Z]+"
should contains only "[a-z]+"
Should contains only "[a-zA-Z]+"
123 contains only "\d+"
123as contains only "[a-z\d]+"
123AS contains only "[A-Z\d]+"
123aS contains only "[a-zA-Z\d]+"