We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Regex Substitution
Regex Substitution
Sort by
recency
|
308 Discussions
|
Please Login in order to post a comment
TIL about lookahead and lookbehind.
The compact "code golf" version…
The somewhat easier to read version…
The somewhat easier to read version…
I've yet to see a HackerRank challenge requiring the "
N
" parameter on the first line of the input. I always read all lines in and skip the first one.n = int(input()) pattern = r'(?<= )(&&|||)(?= )' for _ in range(n): a = input() s = re.sub(pattern, lambda m: 'and' if m.group(0) == '&&' else 'or',a) print(s)
Here is HackerRank Regex Substitution in Python solution - https://programmingoneonone.com/hackerrank-regex-substitution-solution-in-python.html
and_pattern = "(?<= )\&\&(?= )" or_pattern = "(?<= )||(?= )"
Explanation: (?<= ) is a look behind positive. This ensures the characters are preceeded by a space. (?= ) is a look ahead positive. This ensures the characters are followed by a space. Finally, the string in question contains characters which themselves are used in regex statement, so they must be escaped with a backslash to be recognized!
import re
def replace_operators(text): text = re.sub(r'(?<=\s)||(?=\s)', 'or', text) text = re.sub(r'(?<=\s)&&(?=\s)', 'and', text) return text
N = int(input()) text = "\n".join(input() for _ in range(N)) result = replace_operators(text) print(result)