mariadb 在Python中,如何将字符串的这一部分与正则表达式匹配,而不需要固定宽度的模式?

ni65a41a  于 2022-11-08  发布在  Python
关注(0)|答案(1)|浏览(64)

我想从create Table语句中提取名称,例如:
“创建或替换临时表(如果不存在)作者(“
此处的名称是author。如果您查看官方mariaDB文档,您会注意到OR REPLACE、TEMPORARY和IF NOT EXISTS是可选参数。
我想出的正则表达式:

r"(?<=(create)\s*(or replace\s*)?(temporary\s*)?(table)\s*(if not exists\s*)?)(\w+)(?=(\s*)?(\())"

每个单词之间需要多少空格也没有上限,但至少需要一个。
当我在https://regexr.com/上尝试这个正则表达式时,它可以与这些示例一起工作(带有不区分大小写、多行和全局的标志):

CREATE TABLE book (
CREATE OR REPLACE TABLE IF NOT EXISTS author(
CREATE OR REPLACE TEMPORARY TABLE IF NOT EXISTS publisher (

第一次
但是如果我尝试在python中这样做:

import re
firstRow = "CREATE OR REPLACE TABLE IF NOT EXISTS author ("
res = re.search(r"(?<=(create)\s(or replace\s)?(temporary\s)?(table)\s(if not exists\s)?)(\w+)(?=(\s)?(\())", firstRow, re.IGNORECASE)

它会抛出以下错误消息:

Traceback (most recent call last):
  File "test.py", line 116, in <module>
    res = re.sub(r"(?<=(create)\s(or replace\s)?(temporary\s)?(table)\s(if not exists\s)?)(\w+)(?=(\s)?(\())", firstRow, re.IGNORECASE)
  File "C:\Users\stefa\AppData\Local\Programs\Python\Python38-32\lib\re.py", line 210, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "C:\Users\stefa\AppData\Local\Programs\Python\Python38-32\lib\re.py", line 304, in _compile
    p = sre_compile.compile(pattern, flags)
  File "C:\Users\stefa\AppData\Local\Programs\Python\Python38-32\lib\sre_compile.py", line 768, in compile
    code = _code(p, flags)
  File "C:\Users\stefa\AppData\Local\Programs\Python\Python38-32\lib\sre_compile.py", line 607, in _code
    _compile(code, p.data, flags)
  File "C:\Users\stefa\AppData\Local\Programs\Python\Python38-32\lib\sre_compile.py", line 182, in _compile
    raise error("look-behind requires fixed-width pattern")
re.error: look-behind requires fixed-width pattern
qgelzfjb

qgelzfjb1#

它的工作方式与您选择的Javascript相同,Javascript可能是lookbehindAssert中的support无限量词。
由于您已经在使用捕获组,因此根本不需要任何查找,这样就可以匹配表名周围的内容。
由于所有的\s*都是可选的,您可以考虑使用单词边界\b来防止部分单词匹配。

\bcreate\b\s*(?:or replace\s*(?:\btemporary\s*)?)?\btable\s*(?:\bif not exists\s*)?\b(\w+)\s*\(

Regex demo

相关问题