我有一些 SQL 字符串,我想从中找到字符 %s 出现的次数。
示例字符串:
query_fetch_user = """select * from users where id=%s and email LIKE '%sayhello%' """
在这里,我只想获得 %s 的确切计数,并且我想避免将电子邮件部分计入计数。
我试过的。
query_fetch_user.count("%s")
这算作 2
count = start = 0
while True:
start = query_fetch_user.find(sub, start) + 1
if start > 0:
count+=1
else:
print(count)
这也算作 2
但实际计数应该是1。
最佳答案
您可以尝试改用此 RegEx:
\B%s\b
它只会匹配独立的单词(像 =
或 '
这样的符号不计入那个)并且如果它在一个新行上,它不会中断,结束字符串的一行或结尾。 Regex101 .
解释:
\B - Starts where \b does not match - essentially to find where there is a non-word character in front of the text (the start of the line, just after a linebreak, start of the String, period, space, etc)
%s - the String itself (in this case the literal `%s`)
\b - and ends at the word boundary - meaning where the word ends
关于python - 如何在 python 中的字符串中找到 %s 的确切出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48058717/