-1

I want this string:

378282246310005

With a regex, I want to return groups of 4 characters, then the next 6, then the next 5. Like this:

3782 822463 10005

Edit

I also want to have partial matches, so this string:

378 will return 378

and

37822822 will return 3782 822

4

3 回答 3

4

Read about matching digits and quantifiers.

\d is a shorthand character class matching one digit

{Min,Max} is matching at least Min and at most Max times. {x} is matching x times.

You would need also Anchors, either ^ and $ when the number is the complete string or wordboundaries \b before and ahead, when the number is somewhere in the text.

Then you need to capture the matched groups, to be able to retrive the result.

Then you end up here:

^(\d{4})(\d{6})(\d{5})$

Your numbers are then in the capturing groups 1, 2 and 3.

For your partial match requirement you can use this:

^(\d{1,4})(\d{0,6})(\d{0,5})$

See it here on Regexr

于 2013-09-19T07:57:42.890 回答
4

With respect to the partial matches requirement, I guess the regex you're looking for should be like this:

  /(^\d{1,4})(?:(\d{1,6})(\d{1,5})?)?/

Test:

> 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"]
于 2013-09-19T08:41:12.077 回答
1

This should do the trick:

/^(.{4})(.{6})(.{5})$/

If you specifically want to match digits, replace . with \d

Source: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

EDIT: Since you also want partial matching, you can do this:

 /^(.{1,4})(.{0,6})(.{0,5})$/
于 2013-09-19T07:56:51.803 回答