Regex that matches punctuation at the word boundary including underscore

前端 未结 2 1370
灰色年华
灰色年华 2020-12-20 00:34

I am looking for a Python regex for a variable phrase with the following properties: (For the sake of example, let\'s assume the variable phrase here is taking the value

2条回答
  •  情话喂你
    2020-12-20 01:07

    Here is a regex that might solve it:

    Regex

    (?<=[\W_]+|^)and(?=[\W_]+|$)
    

    Example

    # import regex
    
    string = 'this_And'
    test = regex.search(r'(?<=[\W_]+|^)and(?=[\W_]+|$)', string.lower())
    print(test.group(0))
    # prints 'and'
    
    # No match
    string = 'Andy'
    test = regex.search(r'(?<=[\W_]+|^)and(?=[\W_]+|$)', string.lower())
    print(test)
    # prints None
    
    strings = [ "this_and", "this.and", "(and)", "[and]", "and^", ";And"]
    [regex.search(r'(?<=[\W_]+|^)and(?=[\W_]+|$)', s.lower()).group(0) for s in strings if regex.search(r'(?<=[\W_]+|^)and(?=[\W_]+|$)', s.lower())]
    # prints ['and', 'and', 'and', 'and', 'and', 'and']
    

    Explanation

    [\W_]+ means we accept before (?<=) or after (?=) and only non-word symbols except the underscore _ (a word symbol that) is accepted. |^ and |$ allow matches to lie at the edge of the string.

    Edit

    As mentioned in my comment, the module regex does not yield errors with variable lookbehind lengths (as opposed to re).

    # This works fine
    # import regex
    word = 'and'
    pattern = r'(?<=[\W_]+|^){}(?=[\W_]+|$)'.format(word.lower())
    string = 'this_And'
    regex.search(pattern, string.lower())
    

    However, if you insist on using re, then of the top of my head I'd suggest splitting the lookbehind in two (?<=[\W_])and(?=[\W_]+|$)|^and(?=[\W_]+|$) that way cases where the string starts with and are captured as well.

    # This also works fine
    # import re
    word = 'and'
    pattern = r'(?<=[\W_]){}(?=[\W_]+|$)|^{}(?=[\W_]+|$)'.format(word.lower(), word.lower())
    string = 'this_And'
    re.search(pattern, string.lower())
    

提交回复
热议问题