What is a regex to match ONLY an empty string?

后端 未结 10 1557
忘掉有多难
忘掉有多难 2020-12-01 13:24

There are lots of posts about regexs to match a potentially empty string, but I couldn\'t readily find any which provided a regex which only matched an emp

相关标签:
10条回答
  • 2020-12-01 14:00

    Based on the most-approved answer, here is yet another way:

    var result = !/[\d\D]/.test(string);  //[\d\D] will match any character
    
    0 讨论(0)
  • 2020-12-01 14:01

    I would use a negative lookahead for any character:

    ^(?![\s\S])
    

    This can only match if the input is totally empty, because the character class will match any character, including any of the various newline characters.

    0 讨论(0)
  • 2020-12-01 14:06

    Try looking here: https://docs.python.org/2/library/re.html

    I ran into the same problem you had though. I could only build a regex that would match only the empty string and also "\n". Try trimming/replacing the newline characters in the string with another character first.

    I was using http://pythex.org/ and trying weird regexes like these:

    ()

    (?:)

    ^$

    ^(?:^\n){0}$

    and so on.

    0 讨论(0)
  • 2020-12-01 14:07

    As explained in http://www.regular-expressions.info/anchors.html under the section "Strings Ending with a Line Break", \Z will generally match before the end of the last newline in strings that end in a newline. If you want to only match the end of the string, you need to use \z. The exception to this rule is Python.

    In other words, to exclusively match an empty string, you need to use /\A\z/.

    0 讨论(0)
  • 2020-12-01 14:10

    I believe Python is the only widely used language that doesn't support \z in this way (yet). There are Python bindings for Russ Cox / Google's super fast re2 C++ library that can be "dropped in" as a replacement for the bundled re.

    There's an excellent discussion (with workarounds) for this at Perl Compatible Regular Expression (PCRE) in Python, here on SO.

    python
    Python 2.7.11 (default, Jan 16 2016, 01:14:05) 
    [GCC 4.2.1 Compatible FreeBSD Clang 3.4.1 on freebsd10
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import re2 as re
    >>> 
    >>> re.match(r'\A\z', "")
    <re2.Match object at 0x805d97170>
    

    @tchrist's answer is worth the read.

    0 讨论(0)
  • 2020-12-01 14:15

    ^$ -- regex to accept empty string.And it wont match "/n" or "foobar/n" as you mentioned. You could test this regex on https://www.regextester.com/1924.

    If you have your existing regex use or(|) in your regex to match empty string. For example /^[A-Za-z0-9&._ ]+$|^$/

    0 讨论(0)
提交回复
热议问题