Регулярное выражение для замены первой найденной буквы в слове
Вот регулярное выражение которое заменяет все буквы "а" на "о" в строке:
import re
sentence = 'Saame kind of raandom sentence!'
result = re.sub(r'a', 'o', sentence)
print(result)
Но как заменить только первую встреченную букву в каждом слове, а не все буквы в целом предложений? То бишь:
input: Same kind of random sentence!
output: Some kind of rondom sentence!
Ответы (2 шт):
Автор решения: dIm0n
→ Ссылка
Заменить найденное этим:
^([^a]*)a(.*)$
Вот этим:
\g<1>o\g<2>
Тест https://regex101.com/r/QyYwVU/1
Сгенерированный код:
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"^([^a]*)a(.*)$"
test_str = "Same kind of random sentence!"
subst = "\\g<1>o\\g<2>"
# 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.
Для первой буквы в каждом слове можно использовать variable-width negative lookbehind, который поддерживается в стороннем модуле regex:
import regex
re = r'(?<!\w*a\w*)a'
test_str = 'Same kind of random sentence!\naab bba xaxxaa xxx\naaaaaaaaa bbbaaaaaabbbbbb'
subst = r'o'
result = regex.sub(re, subst, test_str, 0, regex.MULTILINE)
if result:
print(result)
Автор решения: MiniMax
→ Ссылка
import re
sentence = 'Saame kind of a raandom aaaa sentence! vvavaa'
result = re.sub('a(\w*)', r'o\1', sentence)
print(result)
Результат
Soame kind of o roandom oaaa sentence! vvovaa