python - 如何在有条件的字符串之间添加字符

标签 python regex

  • 如果字符串中有 %20,它必须用 OR 替换,abc %20 def。预计出 --> '*abc* OR *def*'
  • 如果 , 在字符串中它必须用 OR, abc,def 替换。: 预期输出 --> '*abc* OR *def*'
  • string = 'abc def': 需要更新每个字符串的开头和结尾的字符串 * 用 OR 替换空格。:预期输出 --> '*abc* OR *def*'
  • string = 'abc or def', 'abc+def','abc + def', 'abc OR def': 如果 OR,+ 在字符串中,那么我们需要更新。: 预期输出 --> '*abc* OR *def*'
  • string = 'abc&def','abc & def', 'abc and def' abc AND def': 如果 AND,& 在字符串中,那么我们需要更新。: 预期输出 --> '*abc* AND *def*'
  • string = 'abc', : 预期输出 --> '*abc*
  • string = 'abc def ghi': 预期输出 --> '*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 , + , %20group4 :(&|and|AND)捕获 & , and , ANDgroup5 :\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/

    相关文章:

    python - 使用具有不同项目大小的 Py_buffer 和 PyMemoryView_FromBuffer

    regex - 常规列表indexOf

    python - 自动复制网页到剪贴板

    python - 转发 __getitem__ 到 getattr

    python - sqlite3 连接 python 完整路径失败,在命令行中工作

    Java String.split() 分割每个字符而不是给定的正则表达式

    php - 通过正则表达式从background-image属性获取URL

    python - 在 Python 中使用 RegEx 的函数解析器

    php - 我怎样才能阻止它变得贪婪

    python - Pycharm 说 "tarfile.ReadError: file could not be opened successfully"