regex function that eliminates comments in a string

Viewed 110

Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out. Example: Given an input string of:

apples, pears # and bananas
grapes
bananas !apples

The output expected would be:

apples, pears
grapes
bananas

My Function:

    import regex
    
    def solution(string,markers):
    
        i = regex.sub('{}.*|\s*{}.*'.format(*markers),'',string)
    
        return i

1) solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])

Ideal Result: "apples, pears\ngrapes\nbananas"

Actual Result: 'apples, pears \ngrapes\nbananas' Error: There's a space after 'pears'

2) solution("a #b\nc\nd $e f g", ["#", "$"])

Ideal Result: "'a\nc\nd"

Actual Result: 'a \nc\nd $e f g' Error: There's a space after 'a' and '(space)$e f g' shouldn't be there

1 Answers

Proposed solution:

  1. use simple re. It has all you need in this case,
  2. You dont need (whatever)|\s*(whatever). The first alternative is redundant,
  3. Use (marker1|marker2|...|markern) for comment markers formed by "|".join*(). Why not character class? Because a comment marker can consist of more than one character, i.e. //,
  4. Escape comment markers for regex with re.escape(),
  5. Use $ assertion with re.M flag to reach the end of the comment string.

Python 3:

import re
def solution(string: str, markers: list) -> str:
    return re.sub('\s*(' + '|'.join(map(lambda str: re.escape(str), markers)) + ').*$', '', string, 0, re.M)

# Test:
print (solution('apples, pears # and bananas\ngrapes\nbananas !apples', ['#', '!']))
print (solution('a #b\nc\nd $e f g', ['#', '$']))
Related