如何检查正则表达式字符串是否符合PCRE?

问题描述 投票:0回答:1

在Lua中,有没有办法检查字符串是否是有效的PCRE模式

示例:

local function is_valid_regex(pattern)
  -- Check if the pattern is PCRE-compliant
end

-- Test
print(is_valid_regex(".*"))       -- true
print(is_valid_regex("[a-z]+"))   -- true
print(is_valid_regex("([0-9]"))   -- false (unbalanced parentheses)
print(is_valid_regex("*invalid")) -- false (invalid usage of *)
regex lua
1个回答
0
投票

感谢@InSync的建议:)这个游戏让我了解了可能的解决方案。

可以简单地使用 REGEX 引擎和 pcall(~try-catch)模式创建块。

使用

rex_pcre
模块的示例:

local rex = require("rex_pcre")

local function is_valid_regex(pattern)
    return pcall(rex.new, pattern)
end

-- Test
print(is_valid_regex(".*"))       -- true
print(is_valid_regex("[a-z]+"))   -- true
print(is_valid_regex("([0-9]"))   -- false (unbalanced parentheses)
print(is_valid_regex("*invalid")) -- false (invalid usage of *)
© www.soinside.com 2019 - 2024. All rights reserved.