关键词存在并且在i之前没有特定字符的情况下,返回True的正则表达式

2024-10-01 02:23:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我是这里的新手,希望用Python编写一个regex,如果找到了搜索关键字并且前面没有特定字符,那么它将返回True

基本上,如果它不包含“--”特定搜索关键字之前的任何位置,则返回True,因为“--”表示SQL语法中的注释。你知道吗

例如:

s1 = "from tblEmployee e"
s2 = "--from tblEmployee e"
s3 = "from tblDepartment --tblEmployee e"
s4 = "from tblEmployee e --sample comment"

考虑到上面的场景,如果我们要查找“tbl\u Employee”关键字,它只会为s1和s4返回True。你知道吗

有可能吗?你知道吗

如有任何建议,将不胜感激。你知道吗

谢谢!你知道吗

编辑: 搜索关键字应完全匹配,包括大小写:

例如:

s5 = "from tblEmployee1 e"
s6 = "from tblEmployee1"
s7 = "from TBLEmployee e"

s5、s6和s7将返回False。你知道吗


Tags: fromtruesql语法关键字字符regexs4
1条回答
网友
1楼 · 发布于 2024-10-01 02:23:26

对于正则表达式,反向匹配并不是一件简单的事情。不过,您可以这样做:

import re

def kw_in_s(kw, s):
    pat = r'^((?! ).)*\b{}\b.*'.format(kw)
    return bool(re.match(pat, s))

# '(?! )': negative look-ahead, matches only if not followed by ' '
# '((?! ).)*': zero or more characters none of which is followed by ' '
# '\b{}\b': keyword formatted between two word boundaries

>>> kw_in_s('tblEmployee', " from tblEmployee e")
False
>>> kw_in_s('tblEmployee', "from tblEmployee e")
True
>>> kw_in_s('tblEmployee', "from tblDepartment  tblEmployee e")
False
>>> kw_in_s('tblEmployee', "from tblEmployee e  sample comment")
True
>>> kw_in_s('tblEmployee', "from tblDepartment tblEmployee1 e")
False

Python regular expression syntax docs.

相关问题 更多 >