当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Regex for empty, whitespace or zero

问题描述:

String = ""

String = " "

String = "0"

I need regex to match all three scenario.

I got the first two as /^$|\s+/

How do I include the check for the zero?

网友答案:

This will match the empty string, a single zero, or all whitespace:

/^(\s+|0)?$/

Debuggex Demo

Explanation:

  • / delimiter
  • ^ start of the string
  • ( start a group:
    • \s+ one or more spaces
    • | or
    • 0 a zero
    • ) end the group
  • ? match the preceding group zero or one times
  • $ end of the string
  • / delimiter
网友答案:

Your pattern will match any string that contains any whitespace (e.g. it would consider "foo bar" a match because of the space in the middle). It doesn't sound like this is what you want.

To match any string that contains only whitespace, a single 0, or the empty string, use this:

/^\s*$|^0$/

Or this:

/^(\s*|0)$/
网友答案:

You could try something like :

/^[0\ ]*$/

Or :

/^(\ |0)*$/

If we don't want to match "00000[...]" or "0 0 0 0[...]" :

/^(\ *|0)$/ 
分享给朋友:
您可能感兴趣的文章:
随机阅读: