简体   繁体   English

如何在javascript中有效地匹配字符串中间的数字?

[英]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. 然后是4位数字。 Number of letters may vary but number of digits are same = 4 字母数可能有所不同,但数字位数相同= 4

Now I need to match the first 2 positions from the digits. 现在,我需要匹配数字中的前2个位置。 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. string.match(regexp)之类的东西我在regex模式中很笨。 How can I find the first two digits from 4 digits from above strings ? 如何从上述字符串的4位数字中找到前两位数字? Also it would be great it the solution can match digits without hyphens like XXX 1234 But this is optional. 如果解决方案可以匹配不带连字符的数字,例如XXX 1234那也很棒,但这是可选的。

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* . 尝试查找至少一个字母[a-zA-Z]+的正则表达式,如果需要\\s*话,再加上一些空格\\s* ,再加上连字符- ,然后根据需要\\s*话再加上一些空格\\s* It then matches the first two digits \\d{2} after the pattern.: 然后,它匹配模式后的前两位\\d{2}

[a-zA-Z]+\s*-\s*(\d{2})

may vary but number of digits are same = 4 可能有所不同,但位数相同= 4
Now I need to match the first 2 positions from the digits. 现在,我需要匹配数字中的前2个位置。

Also it would be great it the solution can match digits without hyphens like XXX 1234 But this is optional. 如果解决方案可以匹配不带连字符的数字,例如XXX 1234那也很棒,但这是可选的。

Do you really need to check it starts with letters? 您真的需要检查字母开头吗? How about matching ANY 4 digit number, and capturing only the first 2 digits? 如何匹配任意4位数字并仅捕获前2位数字?

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: 如果末尾总是有4位数字,则可以将其切成薄片:

str.trim().slice(-4,-2);

here's a jsfiddle with the example strings: https://jsfiddle.net/mckinleymedia/6suffmmm/ 这是带有示例字符串的jsfiddle: https ://jsfiddle.net/mckinleymedia/6suffmmm/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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