简体   繁体   中英

How to match digit in middle of a string efficiently in javascript?

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.

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})

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:

Code

 var regex = /\\b(\\d{2})\\d{2}\\b/; var str = 'ABCDE 4321'; var result = str.match(regex)[1]; document.body.innerText += result; 

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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