What is a regex to match ONLY an empty string?

后端 未结 10 1558
忘掉有多难
忘掉有多难 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:15

    As @Bohemian and @mbomb007 mentioned before, this works AND has the additional advantage of being more readable:

    console.log(/^(?!.)/s.test("")); //true

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

    The answer may be language dependent, but since you don't mention one, here is what I just came up with in js:

     var a = ['1','','2','','3'].join('\n');
    
     console.log(a.match(/^.{0}$/gm)); // ["", ""]
    
     // the "." is for readability. it doesn't really matter
     a.match(/^[you can put whatever the hell you want and this will also work just the same]{0}$/gm)
    

    You could also do a.match(/^(.{10,}|.{0})$/gm) to match empty lines OR lines that meet a criteria. (This is what I was looking for to end up here.)

    I know that ^ will match the beginning of any line and $ will match the end of any line

    This is only true if you have the multiline flag turned on, otherwise it will only match the beginning/end of the string. I'm assuming you know this and are implying that, but wanted to note it here for learners.

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

    Wow, ya'll are overthinking it. It's as simple as the following. Besides, many of those answers aren't understood by the RE2 dialect used by C and golang.

    ^$
    
    0 讨论(0)
  • 2020-12-01 14:26

    Another possible answer considering also the case that an empty string might contain several whitespace characters for example spaces,tabs,line break characters can be the folllowing pattern.

    pattern = r"^(\s*)$"

    This pattern matches if the string starts and ends with zero or more whitespace characters.

    It was tested in Python 3

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