我想要这个字符串:
378282246310005
使用正则表达式,我想返回4个字符的组,然后是接下来的6个字符,然后是下一个5.这样:
3782 822463 10005
修改
我也想要部分匹配,所以这个字符串:
378
将返回378
和
37822822
将返回3782 822
答案 0 :(得分:4)
了解匹配的数字和quantifiers。
\d
是匹配一位数的shorthand character class
{Min,Max}
匹配至少Min和最多Max次。 {x}
匹配x次。
当数字为完整字符串时,您还需要Anchors,^
和$
,或者前后数字wordboundaries \b
在文本的某个地方。
然后你需要capture the matched groups,以便能够检索结果。
然后你到此为止:
^(\d{4})(\d{6})(\d{5})$
您的号码将在捕获组1,2和3中。
对于部分匹配要求,您可以使用:
^(\d{1,4})(\d{0,6})(\d{0,5})$
答案 1 :(得分:4)
关于部分匹配要求,我猜你正在寻找的正则表达式应该是这样的:
/(^\d{1,4})(?:(\d{1,6})(\d{1,5})?)?/
测试:
> r = /(^\d{1,4})(?:(\d{1,6})(\d{1,5})?)?/
> s = "378282246310005"
> while(s) { console.log(s.match(r)); s = s.substr(0, s.length - 1) }
["378282246310005", "3782", "822463", "10005", index: 0, input: "378282246310005"]
["37828224631000", "3782", "822463", "1000", index: 0, input: "37828224631000"]
["3782822463100", "3782", "822463", "100", index: 0, input: "3782822463100"]
["378282246310", "3782", "822463", "10", index: 0, input: "378282246310"]
["37828224631", "3782", "822463", "1", index: 0, input: "37828224631"]
["3782822463", "3782", "822463", undefined, index: 0, input: "3782822463"]
["378282246", "3782", "82246", undefined, index: 0, input: "378282246"]
["37828224", "3782", "8224", undefined, index: 0, input: "37828224"]
["3782822", "3782", "822", undefined, index: 0, input: "3782822"]
["378282", "3782", "82", undefined, index: 0, input: "378282"]
["37828", "3782", "8", undefined, index: 0, input: "37828"]
["3782", "3782", undefined, undefined, index: 0, input: "3782"]
["378", "378", undefined, undefined, index: 0, input: "378"]
["37", "37", undefined, undefined, index: 0, input: "37"]
["3", "3", undefined, undefined, index: 0, input: "3"]
答案 2 :(得分:1)
这应该可以解决问题:
/^(.{4})(.{6})(.{5})$/
如果您特别想要匹配数字,请将.
替换为\d
来源:https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
编辑: 由于您还需要部分匹配,因此可以执行以下操作:
/^(.{1,4})(.{0,6})(.{0,5})$/