Reputation: 2169
I am trying to get a serial number from a zigbee packet (i.e get from 702442500 *13*32*702442500#9).
So far, I've tried this:
test = "*#*0##*13*32*702442500#9##";
test.match("\*#\*0##\*13\*32\*(.*)#9##");
And this: test.match("*#*0##*13*32*(.*)#9##");
With no luck. How do I get a valid regular expression that does what I want?
Upvotes: 0
Views: 130
Reputation: 11171
The easiest way to grab that portion of the string would be to use
var regex = /(\*\d{3,}#)/g,
test = "*13*32*702442500#9";
var match = test.match(regex).slice(1,-1);
This captures a *
followed by 3 or more \d
(numbers) until it reaches an octothorpe. Using the global (/g
) modifier will cause it to return an array of matches.
For example, if
var test = "*13*32*702442500#9
*#*0##*13*32*702442500#9##";
then, test.match(regex)
will return ["*702442500#", "*702442500#"]
. You can then slice the elements of this array:
var results = [],
test = "... above ... ",
regex = /(\*\d{3,}#)/g,
matches = test.match(regex);
matches.forEach(function (d) {
results.push(d.slice(1,-1));
})
// results : `["702442500", "702442500"]`
Upvotes: 1
Reputation: 89584
If you want to extract the big number, you can use:
/\*#\*0##\*13\*32\*([^#]+)#9##/
Note that I use delimiters /
that are needed to write a pattern in Javascript (without the regexp object syntax). When you use this syntax, (double)? quotes are not needed. I use [^#]+
instead of .*
because it is more clear and more efficent for the regex engine.
Upvotes: 1
Reputation: 174796
The below regex matches the number which has atleast three digits,
/([0-9][0-9][0-9]+)/
Upvotes: 1