简体   繁体   English

如何使用RegEx忽略第一个句点并匹配所有后续句点?

[英]How to use RegEx to ignore the first period and match all subsequent periods?

How to use RegEx to ignore the first period and match all subsequent periods? 如何使用RegEx忽略第一个句点并匹配所有后续句点?

For example: 例如:

  • 1.23 (no match) 1.23(不匹配)
  • 1.23.45 (matches the second period) 1.23.45(与第二期相匹配)
  • 1.23.45.56 (matches the second and third periods) 1.23.45.56(匹配第二和第三期)

I am trying to limit users from entering invalid numbers. 我试图限制用户输入无效数字。 So I will be using this RegEx to replace matches with empty strings. 所以我将使用此RegEx替换空字符串匹配。

I currently have /[^.0-9]+/ but it is not enough to disallow . 我目前有/ [ /[^.0-9]+/但不足以禁止. after an (optional) initial . 在(可选)初始之后.

Constrain the number between the start ^ and end anchor $ , then specify the number pattern you require. 约束start ^和end anchor $之间的数字,然后指定所需的数字模式。 Such as: 如:

/^\\d+\\.?\\d+?$/

Which allows 1 or more numbers, followed by an optional period, then optional numbers. 其中包含一个或多个数字,后跟可选的句点,然后是可选的数字。

I suggest using a regex that will match 1+ digits, a period, and then any number of digits and periods capturing these 2 parts into separate groups. 我建议使用一个匹配1+数字,一个句点,然后将任意数量的数字和句点匹配到这两个部分的正则表达式。 Then, inside a replace callback method, remove all periods with an additional replace : 然后,在替换回调方法中,删除所有具有额外replace句点:

 var ss = ['1.23', '1.23.45', '1.23.45.56']; var rx = /^(\\d+\\.)([\\d.]*)$/; for (var s of ss) { var res = s.replace(rx, function($0,$1,$2) { return $1+$2.replace(/\\./g, ''); }); console.log(s, "=>", res); } 

Pattern details : 图案细节

  • ^ - start of string ^ - 字符串的开头
  • (\\d+\\.) - Group 1 matching 1+ digits and a literal . (\\d+\\.) - 第1组匹配1+位数和一个文字.
  • ([\\d.]*) - zero or more chars other than digits and a literal dot ([\\d.]*) - 除数字和文字点之外的零个或多个字符
  • $ - end of string. $ - 结束字符串。

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

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