RegEx для замены определенных слов не в кавычках - PullRequest
3 голосов
/ 16 мая 2019

Я пытаюсь заменить Hello в строке s другим словом, если слово НЕ находится между кавычками, такими как "" или ". Давайте представим, что слово замены - Мэтт,

Это ввод:

s = 'Hello How Are you, "hey Hello", \'ney Hello\'. Hello I\'m great'

Желаемый вывод:

s = 'Matt How are you, "hey Hello", \'ney Hello\'. Matt I\'m great '

Я искал и нашел этот код, и с небольшими изменениями мне удалось успешно заменить слово, но оно работает только с '', а не с '' включенным

import re

def replace_method(match):

    if match.group(1) is None:
        return match.group()

    return match.group().replace("Hello", "Matt")

s = 'Hello How Are you, "hey Hello", \'ney Hello\'. Hello I\'m great'

output = re.sub(r"'[^']*'|([^']*)", replace_method, s)
print(output)

Edit:

Спасибо за ответы, но я упустил объяснить что-то важное (что я впервые заметил в свою защиту после выполнения успешного кода), «очевидно», я не хочу этого предложения:

s = "Hellona, how are you"

стать

s = "Markna, how are you"

Итак, регулярное выражение должно включать то, что слово, которое я пытаюсь заменить, не заменяется NUMBERS или LETTERS .

Ответы [ 3 ]

3 голосов
/ 16 мая 2019

Обратный вызов замены выглядит нормально.

Регулярное выражение должно быть таким

r"('[^']*'|\"[^\"]*\")|\b[Hh]ello\b"

Читаемая версия

   (                             # (1 start)
        ' [^']* '
     |  
        " [^"]* "
   )                             # (1 end)
|  
   \b [Hh]ello \b

Обратите внимание, что я думаю, что группа 1 проверяет обратный вызов
должно быть верно, если группа 1 соответствует.

Не программист на Python, но должно быть что-то вроде

if match.group(1) :
    return match.group()
return "Matt"
1 голос
/ 20 мая 2019

Здесь мы могли бы решить эту проблему с помощью:

([^'"]?)(Hello)([^'"])

который мы можем заменить на:

enter image description here

RegEx

Если это выражение нежелательно, вы можете изменить / изменить выражения в regex101.com .

RegEx Circuit

Вы также можете визуализировать свои выражения в jex.im :

enter image description here

JavaScript Demo

Этот фрагмент показывает, что мы, вероятно, имеем правильное выражение:

const regex = /([^'"]?)(Hello)([^'"])/gm;
const str = `Hello How Are you, "hey Hello", 'ney Hello'. Hello I'm great. "Hello' I'm great`;
const subst = `$1Matt$3`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

Python Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"([^'\"]?)(Hello)([^'\"])"

test_str = "Hello How Are you, \"hey Hello\", 'ney Hello'. Hello I'm great. \"Hello' I'm great"

subst = "\1Matt\3"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

Для исключения Hellona мы можем добавить границу слова:

([^'"]?)(\bHello\b)([^'"])

enter image description here

* * Демонстрация тысяча сорок-девять

const regex = /([^'"]?)(\bHello\b)([^'"])/gm;
const str = `Hello How Are you, "hey Hello", 'ney Hello'. Hello I'm great. "Hello' I'm great. Hellona how are you? `;
const subst = `$1Matt$3`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);
1 голос
/ 16 мая 2019
import re


def replace_word(input, search, replace):
    def replace_method(match):
        if match.group(2) is None:
            return match.group()
        return match.group(2).replace(search, replace)
    expr = re.compile("('[^']*'|\"[^\"]*\")|({})".format(search))
    return re.sub(expr, replace_method, s)

s = 'Hello How Are you, "hey Hello", \'ney Hello\'. Hello I\'m great'

output = replace_word(s, "Hello", "Matt")
print(output)

Вы можете сопоставить все: одинарные или двойные кавычки в группе 1 (('[^']*'|\"[^\"]*\")), затем свое слово в группе 2 ({}, отформатированное с термином search), а затем заменить группу 2 на любуюты хочешь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...