Elegant way to replace substring in a regex with optional groups in Python? The Next CEO of Stack OverflowCapturing optional regex segment with PHPFind and replace String with a substring resultOptimal string literal tokenizing algorithmEval is evil: Dynamic method calls from named regex groups in Python 3Improving CSV filtering with Python using regexJavaScript Regex Test and ReplaceReplace fixed width values over 530px with 100% using RegExpython recursive regex optimizationRecursively replace string placeholders with parameterized phrasesFaster way of replacing strings in large pandas dataframe with regex
How to write the block matrix in LaTex?
What exact does MIB represent in SNMP? How is it different from OID?
Hindi speaking tourist to UK from India
Complex fractions
Was a professor correct to chastise me for writing "Prof. X" rather than "Professor X"?
What does "Its cash flow is deeply negative" mean?
What can we do to stop prior company from asking us questions?
On model categories where every object is bifibrant
Beyond letters and diaries—exercises to explore characters' personalities and motivation
Why does the UK parliament need a vote on the political declaration?
I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin
Why didn't Khan get resurrected in the Genesis Explosion?
Is there a difference between "Fahrstuhl" and "Aufzug"
Why do professional authors make "consistency" mistakes? And how to avoid them?
Anatomically Correct Strange Women In Ponds Distributing Swords
Extending anchors in TikZ
Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?
Keeping you safe
Why does standard notation not preserve intervals (visually)
What flight has the highest ratio of time difference to flight time?
Written every which way
Email Frequency Capping in Marketing Cloud Connect
Elegant way to replace substring in a regex with optional groups in Python?
How do you know when two objects are so called entangled?
Elegant way to replace substring in a regex with optional groups in Python?
The Next CEO of Stack OverflowCapturing optional regex segment with PHPFind and replace String with a substring resultOptimal string literal tokenizing algorithmEval is evil: Dynamic method calls from named regex groups in Python 3Improving CSV filtering with Python using regexJavaScript Regex Test and ReplaceReplace fixed width values over 530px with 100% using RegExpython recursive regex optimizationRecursively replace string placeholders with parameterized phrasesFaster way of replacing strings in large pandas dataframe with regex
$begingroup$
Given a string taken from the following set:
strings = [
"The sky is blue and I like it",
"The tree is green and I love it",
"A lemon is yellow"
]
I would like to constuct a function which replaces subject, color and optional verb from this string with others values.
All strings match a certain regex pattern as follow:
regex = r"(?:The|A) (?P<subject>w+) is (?P<color>w+)(?: and I (?P<verb>w+) it)?"
The expected output of such function would look like this:
repl("The sea is blue", "moon", "white", "hate")
# => "The moon is white"
Here is the solution I come with (I can't use .replace()
because there is edge cases if the string contains the subject twice for example):
def repl(sentence, subject, color, verb):
m = re.match(regex, sentence)
s = sentence
new_string = s[:m.start("subject")] + subject + s[m.end("subject"):m.start("color")] + color
if m.group("verb") is None:
new_string += s[m.end("color"):]
else:
new_string += s[m.end("color"):m.start("verb")] + verb + s[m.end("verb"):]
return new_string
Do you think there is a more straightforward way to implement this?
python python-3.x strings regex
$endgroup$
add a comment |
$begingroup$
Given a string taken from the following set:
strings = [
"The sky is blue and I like it",
"The tree is green and I love it",
"A lemon is yellow"
]
I would like to constuct a function which replaces subject, color and optional verb from this string with others values.
All strings match a certain regex pattern as follow:
regex = r"(?:The|A) (?P<subject>w+) is (?P<color>w+)(?: and I (?P<verb>w+) it)?"
The expected output of such function would look like this:
repl("The sea is blue", "moon", "white", "hate")
# => "The moon is white"
Here is the solution I come with (I can't use .replace()
because there is edge cases if the string contains the subject twice for example):
def repl(sentence, subject, color, verb):
m = re.match(regex, sentence)
s = sentence
new_string = s[:m.start("subject")] + subject + s[m.end("subject"):m.start("color")] + color
if m.group("verb") is None:
new_string += s[m.end("color"):]
else:
new_string += s[m.end("color"):m.start("verb")] + verb + s[m.end("verb"):]
return new_string
Do you think there is a more straightforward way to implement this?
python python-3.x strings regex
$endgroup$
$begingroup$
Do you have to use a regex? If not,split(" ")
the string into words, replace words 1, 3, and possibly 6, then" ".join(...)
it back into a sentence.
$endgroup$
– AJNeufeld
1 hour ago
$begingroup$
What do you mean by 'string contains subject twice'? That doesn't seem like it would match your regex.
$endgroup$
– Reinderien
1 hour ago
$begingroup$
@AJNeufeld This is not possible, actually the sentences are even more dynamic than the examples here and may contain an indefinite number of spaces.
$endgroup$
– Delgan
1 hour ago
$begingroup$
@Reinderien For example,repl("The meloon is orange", "orange", "great", "like")
or simplyrepl("A letter is A", "letter", "B", "fail")
$endgroup$
– Delgan
1 hour ago
add a comment |
$begingroup$
Given a string taken from the following set:
strings = [
"The sky is blue and I like it",
"The tree is green and I love it",
"A lemon is yellow"
]
I would like to constuct a function which replaces subject, color and optional verb from this string with others values.
All strings match a certain regex pattern as follow:
regex = r"(?:The|A) (?P<subject>w+) is (?P<color>w+)(?: and I (?P<verb>w+) it)?"
The expected output of such function would look like this:
repl("The sea is blue", "moon", "white", "hate")
# => "The moon is white"
Here is the solution I come with (I can't use .replace()
because there is edge cases if the string contains the subject twice for example):
def repl(sentence, subject, color, verb):
m = re.match(regex, sentence)
s = sentence
new_string = s[:m.start("subject")] + subject + s[m.end("subject"):m.start("color")] + color
if m.group("verb") is None:
new_string += s[m.end("color"):]
else:
new_string += s[m.end("color"):m.start("verb")] + verb + s[m.end("verb"):]
return new_string
Do you think there is a more straightforward way to implement this?
python python-3.x strings regex
$endgroup$
Given a string taken from the following set:
strings = [
"The sky is blue and I like it",
"The tree is green and I love it",
"A lemon is yellow"
]
I would like to constuct a function which replaces subject, color and optional verb from this string with others values.
All strings match a certain regex pattern as follow:
regex = r"(?:The|A) (?P<subject>w+) is (?P<color>w+)(?: and I (?P<verb>w+) it)?"
The expected output of such function would look like this:
repl("The sea is blue", "moon", "white", "hate")
# => "The moon is white"
Here is the solution I come with (I can't use .replace()
because there is edge cases if the string contains the subject twice for example):
def repl(sentence, subject, color, verb):
m = re.match(regex, sentence)
s = sentence
new_string = s[:m.start("subject")] + subject + s[m.end("subject"):m.start("color")] + color
if m.group("verb") is None:
new_string += s[m.end("color"):]
else:
new_string += s[m.end("color"):m.start("verb")] + verb + s[m.end("verb"):]
return new_string
Do you think there is a more straightforward way to implement this?
python python-3.x strings regex
python python-3.x strings regex
edited 1 hour ago
Reinderien
4,860824
4,860824
asked 2 hours ago
DelganDelgan
222111
222111
$begingroup$
Do you have to use a regex? If not,split(" ")
the string into words, replace words 1, 3, and possibly 6, then" ".join(...)
it back into a sentence.
$endgroup$
– AJNeufeld
1 hour ago
$begingroup$
What do you mean by 'string contains subject twice'? That doesn't seem like it would match your regex.
$endgroup$
– Reinderien
1 hour ago
$begingroup$
@AJNeufeld This is not possible, actually the sentences are even more dynamic than the examples here and may contain an indefinite number of spaces.
$endgroup$
– Delgan
1 hour ago
$begingroup$
@Reinderien For example,repl("The meloon is orange", "orange", "great", "like")
or simplyrepl("A letter is A", "letter", "B", "fail")
$endgroup$
– Delgan
1 hour ago
add a comment |
$begingroup$
Do you have to use a regex? If not,split(" ")
the string into words, replace words 1, 3, and possibly 6, then" ".join(...)
it back into a sentence.
$endgroup$
– AJNeufeld
1 hour ago
$begingroup$
What do you mean by 'string contains subject twice'? That doesn't seem like it would match your regex.
$endgroup$
– Reinderien
1 hour ago
$begingroup$
@AJNeufeld This is not possible, actually the sentences are even more dynamic than the examples here and may contain an indefinite number of spaces.
$endgroup$
– Delgan
1 hour ago
$begingroup$
@Reinderien For example,repl("The meloon is orange", "orange", "great", "like")
or simplyrepl("A letter is A", "letter", "B", "fail")
$endgroup$
– Delgan
1 hour ago
$begingroup$
Do you have to use a regex? If not,
split(" ")
the string into words, replace words 1, 3, and possibly 6, then " ".join(...)
it back into a sentence.$endgroup$
– AJNeufeld
1 hour ago
$begingroup$
Do you have to use a regex? If not,
split(" ")
the string into words, replace words 1, 3, and possibly 6, then " ".join(...)
it back into a sentence.$endgroup$
– AJNeufeld
1 hour ago
$begingroup$
What do you mean by 'string contains subject twice'? That doesn't seem like it would match your regex.
$endgroup$
– Reinderien
1 hour ago
$begingroup$
What do you mean by 'string contains subject twice'? That doesn't seem like it would match your regex.
$endgroup$
– Reinderien
1 hour ago
$begingroup$
@AJNeufeld This is not possible, actually the sentences are even more dynamic than the examples here and may contain an indefinite number of spaces.
$endgroup$
– Delgan
1 hour ago
$begingroup$
@AJNeufeld This is not possible, actually the sentences are even more dynamic than the examples here and may contain an indefinite number of spaces.
$endgroup$
– Delgan
1 hour ago
$begingroup$
@Reinderien For example,
repl("The meloon is orange", "orange", "great", "like")
or simply repl("A letter is A", "letter", "B", "fail")
$endgroup$
– Delgan
1 hour ago
$begingroup$
@Reinderien For example,
repl("The meloon is orange", "orange", "great", "like")
or simply repl("A letter is A", "letter", "B", "fail")
$endgroup$
– Delgan
1 hour ago
add a comment |
1 Answer
1
active
oldest
votes
$begingroup$
import re
regex = re.compile(
r'(The|A) '
r'w+'
r'( is )'
r'w+'
r'(?:'
r'( and I )'
r'w+'
r'( it)'
r')?'
)
def repl(sentence, subject, colour, verb=None):
m = regex.match(sentence)
new = m.expand(rf'1 subject2colour')
if m[3]:
new += m.expand(rf'3verb4')
return new
def test():
assert repl('The sky is blue and I like it', 'bathroom', 'smelly', 'distrust') ==
'The bathroom is smelly and I distrust it'
assert repl('The tree is green and I love it', 'pinata', 'angry', 'fear') ==
'The pinata is angry and I fear it'
assert repl('A lemon is yellow', 'population', 'dumbfounded') ==
'A population is dumbfounded'
Essentially, invert the sections of the regex around which you put groups; they're the things you want to save.
$endgroup$
1
$begingroup$
I did not knowexpand()
, this seems very useful. Thanks!
$endgroup$
– Delgan
54 mins ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216474%2felegant-way-to-replace-substring-in-a-regex-with-optional-groups-in-python%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
import re
regex = re.compile(
r'(The|A) '
r'w+'
r'( is )'
r'w+'
r'(?:'
r'( and I )'
r'w+'
r'( it)'
r')?'
)
def repl(sentence, subject, colour, verb=None):
m = regex.match(sentence)
new = m.expand(rf'1 subject2colour')
if m[3]:
new += m.expand(rf'3verb4')
return new
def test():
assert repl('The sky is blue and I like it', 'bathroom', 'smelly', 'distrust') ==
'The bathroom is smelly and I distrust it'
assert repl('The tree is green and I love it', 'pinata', 'angry', 'fear') ==
'The pinata is angry and I fear it'
assert repl('A lemon is yellow', 'population', 'dumbfounded') ==
'A population is dumbfounded'
Essentially, invert the sections of the regex around which you put groups; they're the things you want to save.
$endgroup$
1
$begingroup$
I did not knowexpand()
, this seems very useful. Thanks!
$endgroup$
– Delgan
54 mins ago
add a comment |
$begingroup$
import re
regex = re.compile(
r'(The|A) '
r'w+'
r'( is )'
r'w+'
r'(?:'
r'( and I )'
r'w+'
r'( it)'
r')?'
)
def repl(sentence, subject, colour, verb=None):
m = regex.match(sentence)
new = m.expand(rf'1 subject2colour')
if m[3]:
new += m.expand(rf'3verb4')
return new
def test():
assert repl('The sky is blue and I like it', 'bathroom', 'smelly', 'distrust') ==
'The bathroom is smelly and I distrust it'
assert repl('The tree is green and I love it', 'pinata', 'angry', 'fear') ==
'The pinata is angry and I fear it'
assert repl('A lemon is yellow', 'population', 'dumbfounded') ==
'A population is dumbfounded'
Essentially, invert the sections of the regex around which you put groups; they're the things you want to save.
$endgroup$
1
$begingroup$
I did not knowexpand()
, this seems very useful. Thanks!
$endgroup$
– Delgan
54 mins ago
add a comment |
$begingroup$
import re
regex = re.compile(
r'(The|A) '
r'w+'
r'( is )'
r'w+'
r'(?:'
r'( and I )'
r'w+'
r'( it)'
r')?'
)
def repl(sentence, subject, colour, verb=None):
m = regex.match(sentence)
new = m.expand(rf'1 subject2colour')
if m[3]:
new += m.expand(rf'3verb4')
return new
def test():
assert repl('The sky is blue and I like it', 'bathroom', 'smelly', 'distrust') ==
'The bathroom is smelly and I distrust it'
assert repl('The tree is green and I love it', 'pinata', 'angry', 'fear') ==
'The pinata is angry and I fear it'
assert repl('A lemon is yellow', 'population', 'dumbfounded') ==
'A population is dumbfounded'
Essentially, invert the sections of the regex around which you put groups; they're the things you want to save.
$endgroup$
import re
regex = re.compile(
r'(The|A) '
r'w+'
r'( is )'
r'w+'
r'(?:'
r'( and I )'
r'w+'
r'( it)'
r')?'
)
def repl(sentence, subject, colour, verb=None):
m = regex.match(sentence)
new = m.expand(rf'1 subject2colour')
if m[3]:
new += m.expand(rf'3verb4')
return new
def test():
assert repl('The sky is blue and I like it', 'bathroom', 'smelly', 'distrust') ==
'The bathroom is smelly and I distrust it'
assert repl('The tree is green and I love it', 'pinata', 'angry', 'fear') ==
'The pinata is angry and I fear it'
assert repl('A lemon is yellow', 'population', 'dumbfounded') ==
'A population is dumbfounded'
Essentially, invert the sections of the regex around which you put groups; they're the things you want to save.
answered 1 hour ago
ReinderienReinderien
4,860824
4,860824
1
$begingroup$
I did not knowexpand()
, this seems very useful. Thanks!
$endgroup$
– Delgan
54 mins ago
add a comment |
1
$begingroup$
I did not knowexpand()
, this seems very useful. Thanks!
$endgroup$
– Delgan
54 mins ago
1
1
$begingroup$
I did not know
expand()
, this seems very useful. Thanks!$endgroup$
– Delgan
54 mins ago
$begingroup$
I did not know
expand()
, this seems very useful. Thanks!$endgroup$
– Delgan
54 mins ago
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216474%2felegant-way-to-replace-substring-in-a-regex-with-optional-groups-in-python%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
$begingroup$
Do you have to use a regex? If not,
split(" ")
the string into words, replace words 1, 3, and possibly 6, then" ".join(...)
it back into a sentence.$endgroup$
– AJNeufeld
1 hour ago
$begingroup$
What do you mean by 'string contains subject twice'? That doesn't seem like it would match your regex.
$endgroup$
– Reinderien
1 hour ago
$begingroup$
@AJNeufeld This is not possible, actually the sentences are even more dynamic than the examples here and may contain an indefinite number of spaces.
$endgroup$
– Delgan
1 hour ago
$begingroup$
@Reinderien For example,
repl("The meloon is orange", "orange", "great", "like")
or simplyrepl("A letter is A", "letter", "B", "fail")
$endgroup$
– Delgan
1 hour ago