Matching an empty string with regex

前端 未结 5 884
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-20 20:36

    ^\s+$ - does that not also work?

    Not for matching an empty string. In general, X+ means X one or more times. So, \s+ cannot match the empty string - it requires at least one \s in order to match.

                                         ^ \s + $
                                         | |  | |
    start of string ---------------------+ |  | |
    whitespace character ------------------+  | |
    one or more of what precedes -------------+ |
    end of string ------------------------------+
    

    Now, X* means X 0 or more times, so ^\s*$ would indeed match an empty string.


    ^\s+$

    enter image description here

    ^\s*$

    enter image description here

提交回复
热议问题