+ 3

Regular expressions

Keep in mind that this is my first time using regular expressions, so please dont judge. I have a code: import re def solution(s, markers): markers = "".join(markers) return re.sub('#[^\n]+', '', s) print(solution("a #b\nc\nd !e f g", ["#", "!"])) I want the # in line 4 to be replaced with an unknown character, is there a way to do it? I tried just putting markers instead of # but that didnt work. I appreciate all the help

20th Jul 2020, 3:48 PM
Kirill
Kirill - avatar
9 Antworten
+ 1
You can use f-strings (or even <string>.format() to interpolate the markers into the strings. So for example, you can change the regex in line 4 from '#[^\n]+' to f"{markers}[^\n]+" (note that the `f` has to be outside the string) But because you want to choose from any one of the markers, enclose the markers in square brackets f"[{markers}][^\n]+"
20th Jul 2020, 4:03 PM
XXX
XXX - avatar
+ 2
XXX okay, thank you very much
20th Jul 2020, 4:34 PM
Kirill
Kirill - avatar
+ 1
XXX thank you so much, that worked, if you have time can yo answer one more question. If I have a whitespace at the end of the line, before the new line, how do I remove it?
20th Jul 2020, 4:06 PM
Kirill
Kirill - avatar
+ 1
XXX the code prints : a b c but after "a" there is a white space. how do I remove all the whitespaces that are only at the end of the line?
20th Jul 2020, 4:16 PM
Kirill
Kirill - avatar
+ 1
I haven't really worked much with regex myself. I just knew the solution to your problem. This is the thread I have started, follow it so you get notified when someone answers.
20th Jul 2020, 4:44 PM
XXX
XXX - avatar
+ 1
Kirill Vidov see this code https://code.sololearn.com/c5ooiYKi4eXG/?ref=app The same thing has been done as before, except now, I am passing the string returned by re.sub to another re.sub which is processing the processed string. In the outer re.sub, I have used the lookahead pattern to match all white spaces followed by a new line. See this link for lookahead operators https://www.rexegg.com/regex-lookarounds.html
20th Jul 2020, 7:36 PM
XXX
XXX - avatar
+ 1
@XXX thank you very mmuch
21st Jul 2020, 9:02 AM
Kirill
Kirill - avatar
0
I didn't really understand what you want. Can you explain with an example?
20th Jul 2020, 4:14 PM
XXX
XXX - avatar
0
Hmm I don't really know how to do that. I tried doing this import re def solution(s, markers): markers = "".join(markers) return re.sub(r'\s\n', '', re.sub(rf'{markers}[^\n]+', '', s)) print(solution("a #b\nc\nd !e f g", ["#", "!"])) But that removes the white space as well as the new line. I'll start a bew QnA thread and send you the link.
20th Jul 2020, 4:34 PM
XXX
XXX - avatar