Regex to *not* match any characters

前端 未结 10 1575
一个人的身影
一个人的身影 2020-12-24 11:18

I know it is quite some weird goal here but for a quick and dirty fix for one of our system we do need to not filter any input and let the corruption go into the system.

相关标签:
10条回答
  • 2020-12-24 11:32

    ^ is only not when it's in class (such as [^a-z] meaning anything but a-z). You've turned it into a literal ^ with the backslash.

    What you're trying to do is [^]*, but that's not legal. You could try something like

    " {10000}"
    

    which would match exactly 10,000 spaces, if that's longer than your maximum input, it should never be matched.

    0 讨论(0)
  • 2020-12-24 11:33

    Empty regex

    The best regex to never match anything is an empty regex. But I'm not sure all regex engine will accept that.

    Impossible regex

    The other solution is to create an impossible regex. I found that $-^ only takes two steps to compute regardless of the size of your text (https://regex101.com/r/yjcs1Z/1).

    For reference:

    • $^ and $. take 36 steps to compute -> O(1)
    • \b\B takes 1507 steps on my sample and increase with the number of character in your string -> O(n)
    0 讨论(0)
  • 2020-12-24 11:36

    Instead of trying to not match any characters, why not just match all characters? ^.*$ should do the trick. If you have to not match any characters then try ^\j$ (Assuming of course, that your regular expression engine will not throw an error when you provide it an invalid character class. If it does, try ^()$. A quick test with RegexBuddy suggests that this might work.

    0 讨论(0)
  • 2020-12-24 11:40

    The ^ character doesn't mean "not" except inside a character class ([]). If you want to not match anything, you could use a negative lookahead that matches anything: (?!.*).

    0 讨论(0)
  • 2020-12-24 11:43
    ((?iLmsux))
    

    Try this, it matches only if the string is empty.

    0 讨论(0)
  • 2020-12-24 11:43

    Eh I know this is a little late, but you could simply not read any input if the regex is empty

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