'*abc* OR *def*'
'*abc* OR *def*'
'*abc* OR *def*'
'*abc* OR *def*'
'*abc* AND *def*'
'*abc*
'*abc* OR *def* OR *ghi*'
代码如下
import re
def format_search_value(search_value_1):
punctuations = '''!()[]{};:"\,<>./?@#%^*~'''
search_value_1 = search_value_1.replace('+', ' ')
#if %20 there in the string it has to replace with OR, abc %20 def
search_value_1 = re.sub('^(%20)+$', '%20', search_value_1)
search_value = ""
for char in search_value_1:
if char not in punctuations:
search_value = search_value + char
search_expression = ','.join([f'*{word.strip()}*' for word in search_value.split(',')])
search_expression = re.sub(' +', ' ', search_expression.replace('%20', ' '))
search_expression = ','.join([f'*{word}*' for word in search_expression.split(' ')])
search_parameter = search_expression.replace('%20', ' OR ').replace(',', ' OR ') \
.replace('and', 'AND').replace('+', 'OR').replace('or', 'OR').strip()
search_parameter = search_parameter.replace('**', '*')
return search_parameter
format_search_value('abc or def')
我只为 ('abc def') 获得了正确的输出,即 '*abc* OR *def*'
最佳答案
在查看了 Kraigolas 和 Will 给出的精彩答案后,我尝试了一种只需要一个正则表达式的不同方法。
输入(从 Will 的回答中窃取:D)
import re
test_cases = (
'abc %20 def',
'abc %20 def',
'abc or def',
'abc OR def',
'abc+def',
'abc + def',
'abc&def',
'abc & def',
'abc AND def',
'abc and def',
)
模式捕获 5 组如下所述。group1
:(\w+)\s?
捕获第一个空格之前的所有字母group2
:((or|OR|\+|%20)|(&|and|AND))
第 3 组和第 4 组的包装组(这使得创建一个正则表达式成为可能)group3
:(or|OR|\+|%20)
捕获 or
, OR
, +
, %20
group4
:(&|and|AND)
捕获 &
, and
, AND
group5
:\s?(\w+)
捕获最后一个空格后的所有字母。请注意
\s?
捕获 1 个或 0 个空格。pattern = re.compile(r'(\w+)\s?((or|OR|\+|%20)|(&|and|AND))\s?(\w+)')
格式化字符串如下。如果第 3 组退出,则替换为 OR
.否则替换为 AND
. (请注意,当第 3 组为空时,第 4 组为非空,反之亦然。)def format_value(text):
match = pattern.match(text)
if match is not None and match.group(3):
return pattern.sub(r'*\1* OR *\5*', text)
else:
return pattern.sub(r'*\1* AND *\5*', text)
for x in test_cases:
print(format_value(x))
输出*abc* OR *def*
*abc* OR *def*
*abc* OR *def*
*abc* OR *def*
*abc* OR *def*
*abc* OR *def*
*abc* AND *def*
*abc* AND *def*
*abc* AND *def*
*abc* AND *def*
编辑 捕获
abc def ghi
这是一个小技巧。创建另一个模式来捕捉空间。这不会捕获两侧带有 * 的已格式化字符串,因为我正在搜索由 2 个单词字符包围的空格。
space_pattern = re.compile(r'(\w)(\s)(\w)')
通过删除前导和尾随星号来更新格式值方法。def format_value(text):
match = pattern.match(text)
if match is not None and match.group(3):
return pattern.sub(r'\1* OR *\5', text)
else:
return pattern.sub(r'\1* AND *\5', text)
如下重新格式化字符串并添加尾部和前导星号。for x in test_cases:
formatted_value = format_value(x)
print("*" + space_pattern.sub(r'\1* OR *\3', formatted_value) + "*")
输出*abc* OR *def*
*abc* OR *def*
*abc* OR *def*
*abc* OR *def*
*abc* OR *def*
*abc* OR *def*
*abc* AND *def*
*abc* AND *def*
*abc* AND *def*
*abc* AND *def*
*abc*
*abc* OR *def* OR *ghi*
关于python - 如何在有条件的字符串之间添加字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68033881/