简体   繁体   English

使用正则表达式从字符串中提取数字部分工作

[英]Number extraction from string using regex working partially

I'm extracting the phone numbers that begin with 9 followed by other 9 digits from tweets using JavaScript. 我正在使用JavaScript从推文中提取以9开头的电话号码,再提取其他9位数字。

Here's the regex pattern I am using: 这是我使用的正则表达式模式:

var numberPattern = /^9[0-9]{9}/;

Here's the pattern matching phase: 这是模式匹配阶段:

var numberstring = JSON.stringify(data[i].text);
        if(numberPattern.test(data[i].text.toString()) == true){

          var obj={
            tweet : {
                status : data[i].text
            },
            phone : numberstring.match(numberPattern)

          }
          //console.log(numberstring.match(numberPattern));
          stringarray.push(obj);

The problem is it is working for few numbers and not all. 问题是它只适用于少数几个而不是全部。 Also, I want to modify the regex to accept +91 prefix to numbers as well and(or) reject a starting 0 in numbers. 另外,我想修改正则表达式以也接受数字的+91前缀和(或)拒绝数字的开头0。 I'm a beginner in regex, so help is needed. 我是regex的初学者,因此需要帮助。 Thanks. 谢谢。

Example: 例:

#Chennai O-ve blood for @arun_scribbles 's friend's father surgery in few days. Pl call 9445866298. 15May. via @arun_scribbles

Your regex pattern seems to be designed to allow a 9 or 8 at the beginning, but it would be better to enclose that choice in parentheses: /^(9|8)[0-9]{9}/ . 您的正则表达式模式似乎设计为允许开头为9或8,但最好将该选择括在括号中: /^(9|8)[0-9]{9}/

To allow an optional "+" at the beginning, follow it with a question mark to make it optional: /^\\+?(9|8)[0-9]{9}/ . 要在开头允许一个可选的“ +”,请在其后加上一个问号使其成为可选: /^\\+?(9|8)[0-9]{9}/

To allow any character except "0", replace the (9|8) with a construct to accept only 1-9: /^\\+?[1-9][0-9]{9}/ . 要允许除“ 0”以外的任何字符,请用一个仅接受1-9的结构替换(9|8)/^\\+?[1-9][0-9]{9}/

And in your example, the phone number doesn't come at the beginning of the line, so the caret will not find it. 在您的示例中,电话号码不在行首,因此插入符号将找不到它。 If you're looking for content in the middle of the line, you'll need to drop the caret: /\\+?[1-9][0-9]{9}/ . 如果要在行的中间查找内容,则需要删除插入符号: /\\+?[1-9][0-9]{9}/

var numberPattern = /([+]91)?9[0-9]{9}\b/;

Try this regex pattern: [\\+]?[0-9]{1,4}[\\s]?[0-9]{10} 尝试以下正则表达式模式: [\\+]?[0-9]{1,4}[\\s]?[0-9]{10}

It accepts any country code with + , a space , and then 10 digit number. 它接受带有+space和10位数字的任何国家/地区代码。

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

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