我正在尝试编写一个程序来验证用类似于 BBcode 的标记语言编写的文档。
这种标记语言既有匹配的 ( [b]bold[/b] text
) 标记,也有不匹配的 ( today is [date]
) 标记。不幸的是,不能选择使用不同的标记语言。
但是,我的正则表达式并没有按照我想要的方式行事。它似乎总是停在第一个匹配的结束标记处,而不是用递归标识该嵌套标记(?R)
。
我正在使用该regex
模块,它支持(?R)
,而不是re
。
我的问题是:
如何有效地使用递归正则表达式来匹配嵌套标签而不终止第一个标签?
如果有比正则表达式更好的方法,那是什么方法?
这是我构建后的正则表达式:
\[(b|i|u|h1|h2|h3|large|small|list|table|grid)\](?:((?!\[\/\1\]).)*?|(?R))*\[\/\1\]
这是一个无法按预期工作的测试字符串:(
[large]test1 [large]test2[/large] test3[/large]
它应该匹配整个字符串,但在 test3 之前停止)
这是 regex101.com 上的正则表达式:https ://regex101.com/r/laJSLZ/1
此测试不需要在几毫秒甚至几秒内完成,但它确实需要能够在 Travis-CI 构建合理的时间内验证大约 100 个文件,每个文件包含 1,000 到 10,000 个字符。
对于上下文,使用此正则表达式的逻辑如下所示:
import io, regex # https://pypi.org/project/regex/
# All the tags that must have opening and closing tags
matching_tags = 'b', 'i', 'u', 'h1', 'h2', 'h3', 'large', 'small', 'list', 'table', 'grid'
# our first part matches an opening tag:
# \[(b|i|u|h1|h2|h3|large|small|list|table|grid)\]
# our middle part matches the text in the middle, including any properly formed tag sets in between:
# (?:((?!\[\/\1\]).)*?|(?R))*
# our last part matches the closing tag for our first match:
# \[\/\1\]
pattern = r'\[(' + '|'.join(matching_tags) + r')\](?:((?!\[\/\1\]).)*?|(?R))*\[\/\1\]'
myRegex = re.compile(pattern)
data = ''
with open('input.txt', 'r') as file:
data = '[br]'.join(file.readlines())
def validate(text):
valid = True
for node in all_nodes(text):
valid = valid and is_valid(node)
return valid
# (Only important thing here is that I call this on every node, this
# should work fine but the regex to get me those nodes does not.)
# markup should be valid iff opening and closing tag counts are equal
# in the whole file, in each matching top-level pair of tags, and in
# each child all the way down to the smallest unit (a string that has
# no tags at all)
def is_valid(text):
valid = True
for tag in matching_tags:
valid = valid and text.count(f'[{tag}]') == text.count(f'[/{tag}]')
return valid
# this returns each child of the text given to it
# this call:
# all_nodes('[b]some [large]text to[/large] validate [i]with [u]regex[/u]![/i] love[/b] to use [b]regex to [i]do stuff[/i][/b]')
# should return a list containing these strings:
# [b]some [large]text to[/large] validate [i]with [u]regex[/u]![/i] love[/b]
# [large]text to[/large]
# [i]with [u]regex[/u]![/i]
# [u]regex[/u]
# [b]regex to [i]do stuff[/i][/b]
# [i]do stuff[/i]
def all_nodes(text):
matches = myRegex.findall(text)
if len(matches) > 0:
for m in matches:
result += all_nodes(m)
return result
exit(0 if validate(data) else 1)