简体   繁体   English

用正则表达式查找三个或四个逗号分隔的数字

[英]Find three or four comma-separated numbers with regexp

Let's say I have a string *White 4,5,6 LOTE Jr. Service Learning Kick-Off (2017-10-6) and want to find a substring matching the regular expression \\d,\\d,\\d|,\\d , corresponding to any group of 3 or 4 numbers separated by commas, and if the regex isn't present, return an empty string. 假设我有一个字符串*White 4,5,6 LOTE Jr. Service Learning Kick-Off (2017-10-6) ,想找到一个匹配正则表达式\\d,\\d,\\d|,\\d的子字符串,对应由3或4个数字组成的任意一组,以逗号分隔,如果不存在正则表达式,则返回一个空字符串。 How can I do this? 我怎样才能做到这一点?

 let str = "*White 4,5,6 LOTE Jr. Service Learning Kick-Off (2017-10-6)"; let re = /\\d,\\d,\\d(?:,\\d)?/; let [numbers] = str.match(re) || ['']; console.log(numbers); 

match will return null if it can't find the pattern; 如果找不到模式,则match将返回null || '' || '' will turn that null into an empty string. || ''会将null转换为空字符串。

Note that I changed your pattern, since yours says "three digits separated by commas - or, a comma and a digit". 请注意,我更改了您的模式,因为您的模式说“用逗号隔开的三个数字-或逗号和一个数字”。

If you actually meant numbers as your text says, and not digits, then use /\\d+,\\d+,\\d+(?:,\\d+)?/ for integers; 如果您实际上是按照文本的意思而不是数字来表示数字,则对整数使用/\\d+,\\d+,\\d+(?:,\\d+)?/ if you need floats or complex numbers, please ask so explicitly (they're quite more... complex). 如果您需要浮点数或复数,请明确要求(它们要复杂得多)。

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

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