Reputation: 8940
I have strings like
XXX-1234
XXXX-1234
XX - 4321
ABCDE - 4321
AB -5677
So there will be letters at the beginning. then there will be hyphen. and then 4 digits. Number of letters may vary but number of digits are same = 4
Now I need to match the first 2 positions from the digits. So I tried a long process.
temp_digit=mystring;
temp_digit=temp_digit.replace(/ /g,'');
temp_digit=temp_digit.split("-");
if(temp_digit[1].substring(0,2)=='12') {}
Now is there any process using regex / pattern matching so that I can do it in an efficient way. Something like string.match(regexp) I'm dumb in regex patterns. How can I find the first two digits from 4 digits from above strings ? Also it would be great it the solution can match digits without hyphens like XXX 1234
But this is optional.
Upvotes: 0
Views: 2603
Reputation: 768
If there are always 4 digits at the end, you can simply slice it:
str.trim().slice(-4,-2);
here's a jsfiddle with the example strings: https://jsfiddle.net/mckinleymedia/6suffmmm/
Upvotes: 0
Reputation: 6511
may vary but number of digits are same = 4
Now I need to match the first 2 positions from the digits.Also it would be great it the solution can match digits without hyphens like
XXX 1234
But this is optional.
Do you really need to check it starts with letters? How about matching ANY 4 digit number, and capturing only the first 2 digits?
Regex
/\b(\d{2})\d{2}\b/
Matches:
\b
a word boundary(\d{2})
2 digits, captured in group 1, and assigned to match[1]
.\d{2}
2 more digits (not captured).\b
a word boundaryCode
var regex = /\b(\d{2})\d{2}\b/;
var str = 'ABCDE 4321';
var result = str.match(regex)[1];
document.body.innerText += result;
Upvotes: 1
Reputation: 3032
Try a regular expression that finds at least one letter [a-zA-Z]+
, followed by some space if necessary \s*
, followed by a hyphen -
, followed by some more space if necessary \s*
. It then matches the first two digits \d{2}
after the pattern.:
[a-zA-Z]+\s*-\s*(\d{2})
Upvotes: 3