简体   繁体   English

验证整个字符串并获得所有匹配项

[英]Validate whole string and get all matches

I'd like to validate my string input if it it contains digits separated by spaces. 我想验证我的字符串输入是否包含以空格分隔的数字。 I tried using the regex 我尝试使用正则表达式

^(\d)(?:\s(\d))*$

and was able to check the validity via the test(String) method, but when I use str.split(regex) it does not give me the correct matches. 并能够通过test(String)方法检查有效性,但是当我使用str.split(regex)它没有给我正确的匹配项。

For example, I have the following input: 例如,我有以下输入:

2 3 4 5

When I try to use the split method, I get 当我尝试使用split方法时,我得到

["", "2", "5", ""]

I was expecting the result to be 我期望结果是

["2", "3", "4", "5"]

Any suggestion is greatly appreciated, thanks! 任何建议,不胜感激,谢谢!

Your ^(\\d)(?:\\s(\\d))*$ regex splits the string correctly as ["", "2", "5", ""] because: 您的^(\\d)(?:\\s(\\d))*$正则表达式将字符串正确分割为["", "2", "5", ""]因为:

  • The first (\\d) captures a digit at the beginning of the string, and inserts it into the resulting array. 第一个(\\d)在字符串的开头捕获一个数字,并将其插入到结果数组中。 Since the digit is found at the beginning, the empty string before the string start and the first digit appears as the first array element, and 2 is the second 由于在开头找到数字,因此在字符串开头之前的空字符串和第一个数字显示为第一个数组元素,而2是第二个数组元素
  • The (?:\\s(\\d))* construct is a * -quantified non-capturing group that matches 0+ sequenes of a whitespace followed with a digit, and the digit is captured . (?:\\s(\\d))*构造是经过*量化的非捕获组,它与空格的0+后缀匹配,后跟一个数字,并且捕获了该数字。 That is, each time a space+digit is matched, the Group 2 slot is re-written with a new value, and the last one is kept that way, which is 5 . 也就是说,每次匹配空格和数字时,第2组插槽都将用新值重写,最后一个将以5方式保留。 Since the right-hand split border happened at the end of the string, the empty string is added to the resulting array. 由于右边的分割边框发生在字符串的末尾,因此将空字符串添加到结果数组中。

If your string is already validated, you need no /\\d+/g , you may just split with a space (note that capturing groups are redundant in your regex then): 如果您的字符串已经通过验证,则不需要/\\d+/g ,您可以仅用一个空格分割(请注意,捕获组在正则表达式中是多余的):

 var s = "2 3 4 5"; if (/^\\d(?:\\s\\d)*$/.test(s)) { console.log(s.split(" ")); } // var s = "2 3 4 a"; won't show any output 

Use the regular expression \\d+ with the global option g (which tells .match to return all matches instead of just the first one): 将正则表达式\\d+与全局选项g一起使用(告诉.match返回所有匹配项,而不仅仅是第一个匹配项):

"2 3 4 5".match(/\\d+/g)

Result: ["2", "3", "4", "5"] 结果: ["2", "3", "4", "5"]


Edit : To test the validity of the input string (requirement: digits separated by spaces), use: 编辑 :要测试输入字符串的有效性(要求:数字用空格分隔),请使用:

(/^(\\d )+\\d?$/).test("1 2 3 4 a")

The (\\d )+ matches any number of repetitions of a digit followed by a space, and \\d? (\\d )+匹配任意数量的重复数字,后跟一个空格,以及\\d? matches a possible trailing digit without a following whitespace character. 匹配可能的尾随数字,但不带空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM