简体   繁体   English

使用正则表达式仅检索7位数的字符串

[英]Using regex to only retrieve string with 7 digits

In short, the page contains about 10 divs, each containing letters and numbers and I'm trying to return all occurrences of exactly 7 digits, but can have other, non-digit characters before and after. 简而言之,页面包含大约10个div,每个div包含字母和数字,我试图返回所有出现的正好7位数,但前后可以有其他非数字字符。

eg. 例如。

"q1234567" should return 1234567 “q1234567”应返回1234567

"q1234567q" should return 1234567 “q1234567q”应返回1234567

"q1234567q1234567q12345678q" should return 1234567 and 1234567 “q1234567q1234567q12345678q”应返回1234567和1234567

"12345678" should NOT be returned 不应退回“12345678”

To be more specific, an example of an entire string: 更具体地说,整个字符串的示例:

q1234567q
q1234567q
q12345678q
q1234567q123456789q123456q1324567q1234567
1234567
1
12
123
1234
12345
q12345q
q1234
12345q
123

I tried doing this via regex and got as far as 我尝试通过正则表达式做到这一点,并得到了

/\d{7}(?=\D|$)/g

but JavaScript doesn't play well with the lookbehind.. How can I get around this without involving a whole new library? 但是JavaScript并不能很好地适应外观。如何在不涉及全新库的情况下解决这个问题?

This regex should work: 这个正则表达式应该工作:

/^\D*\d{7}\D*$/

Online Demo: http://regex101.com/r/nE5eI6 在线演示: http//regex101.com/r/nE5eI6

UPDATE: As per edited question and comments below you can use this regex: 更新:根据下面编辑的问题和评论,您可以使用此正则表达式:

(?:^|\D)(\d{7})(?=\D|$)

And use matched group #1 for your output. 并使用匹配的组#1作为输出。

Demo: http://regex101.com/r/wL4oW1 演示: http//regex101.com/r/wL4oW1

You could maybe use something like this? 你可以使用这样的东西吗?

var regex = /(?:^|\D)(\d{7})(?!\d)/g;
var s = "q1234567q123456789q123456q1324567q1234567";
var match, matches=[];

while ( (match=regex.exec(s)) !== null ) {
    matches.push(match[1]);
}

alert(matches);

jsfiddle demo jsfiddle演示

怎么样: (?<=\\D)[0-9]{7}(?=\\D|$)|^[0-9]{7}(?=\\D|$)

var regex = /(\b|\D)(\d{7})(\b|\D)/g
function get7digits(s) {
    var md, matches=[];
    while( (md=regex.exec(s)) !== null ) matches.push(md[2]);
    return matches;
}

get7digits('q1234567q123456789q123456q1324567q1234567')

["1234567", "1324567"] [“1234567”,“1324567”]

How about this one: 这个怎么样:

/(^|\\D)\\d{7}(\\$|\\D)/gm

http://regex101.com/r/iT5cR3 http://regex101.com/r/iT5cR3

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

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