Matching an empty string with regex

前端 未结 5 866
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 20:21

I\'ve seen posts here on stackoverflow that say that the regex ^$ will match an empty string... So it made me think... why not something like this: ^\\s+$

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-20 20:48

    \s is the character class for whitespace. ^\s+$ would match both "\t\n" and "\t\t". They look empty, but are not. Spaces, tabs, and newlines are characters too! By using ^$, you match the beginning of the string with ^ immediately followed by the end of the string $. Note that matching the regular expression '' will also match empty strings, but match them anywhere.

    Python example:

    empty_string_matches = re.findall('', 'hello world')
    empty_line_matches = re.findall('^$', 'hello world')
    print "Matches for '':", empty_string_matches
    print "Matches for '^$':", empty_line_matches
    

    returns

    Matches for '': ['', '', '', '', '', '', '', '', '', '', '', '']
    Matches for '^$': []
    

    Because there is an empty string between each letter in 'hello world'.

提交回复
热议问题