Python:如何为内联有序列表创建正则表达式?

时间:2014-08-16 19:36:11

标签: python regex django

我有一个表单字段,大多数只包含内联有序列表:

1. This item may be contain characters, symbols or numbers. 2. And this item also...

以下代码不适用于用户输入验证(用户只能输入内联有序列表):

definiton_re = re.compile(r'^(?:\d\.\s(?:.+?))+$')
validate_definiton = RegexValidator(definiton_re, _("Enter a valid 'definition' in format: 1. meaning #1, 2. meaning #2...etc"), 'invalid')

P.S。:这里我使用Django框架中的RegexValidator类来验证表单字段值。

2 个答案:

答案 0 :(得分:1)

Nice solution from OP.为了进一步推动,让我们进行一些正则表达式优化/打高尔夫球。

(?<!\S)\d{1,2}\.\s((?:(?!,\s\d{1,2}\.),?[^,]*)+)

以下是新内容:

  • (?:^|\s)与交替之间的回溯相匹配。在这里,我们使用(?<!\S)来断言我们不在非空白字符前面。
  • \d{1,2}\.\s不必属于非捕获组。
  • (.+?)(?=(?:, \d{1,2}\.)|$)太笨重了。我们将此位更改为:
    • ( 捕获群组
    • (?:
    • (?!否定前瞻:断言我们的立场是
    • ,\s\d{1,2}\.逗号,空白字符,然后是列表索引。
    • )
    • ,?[^,]*以下是有趣的优化:
      • 如果有逗号,我们匹配逗号。因为我们从先行断言中知道这个位置没有启动新的列表索引。因此,我们可以安全地假设非逗号序列的剩余部分(如果有的话)与下一个元素无关,因此我们使用*量词滚动它们,并且没有回溯。 / LI>
      • 这是对(.+?)的重大改进。
    • )+继续重复该组,直到负前瞻断言失败。
    • )

您可以使用它代替the other answer中的正则表达式,这里是regex demo


虽然乍一看,解析时使用re.split()可以更好地解决这个问题:

input = '1. List item #1, 2. List item 2, 3. List item #3.';
lines = re.split('(?:^|, )\d{1,2}\. ', input);
 # Gives ['', 'List item #1', 'List item 2', 'List item #3.']
if lines[0] == '':
  lines = lines[1:];
 # Throws away the first empty element from splitting.
print lines;

这是online code demo

不幸的是,对于验证,您必须遵循正则表达式匹配方法,只需在楼上编译正则表达式:

regex = re.compile(r'(?<!\S)\d{1,2}\.\s((?:(?!,\s\d{1,2}\.),?[^,]*)+)')

答案 1 :(得分:0)

这是我的解决方案。它工作不错。

input = '1. List item #1, 2. List item 2, 3. List item #3.'
regex = re.compile(r'(?:^|\s)(?:\d{1,2}\.\s)(.+?)(?=(?:, \d{1,2}\.)|$)')
# Parsing.
regex.findall(input) # Result: ['List item #1', 'List item 2', 'List item #3.']
# Validation.
validate_input = RegexValidator(regex, _("Input must be in format: 1. any thing..., 2. any thing...etc"), 'invalid')
validate_input(input) # No errors.