简体   繁体   English

用javascript中的正则表达式匹配其他两个字符串之间的字符串

[英]Match a string between two other strings with regex in javascript

How can I use regex in javascript to match the phone number and only the phone number in the sample string below? 如何在javascript中使用正则表达式来匹配电话号码,并且仅匹配下面示例字符串中的电话号码? The way I have it written below matches "PHONE=9878906756", I need it to only match "9878906756". 我在下面编写的方式匹配“ PHONE = 9878906756”,我只需要它匹配“ 9878906756”。 I think this should be relatively simple, but I've tried putting negating like characters around "PHONE=" with no luck. 我认为这应该相对简单,但是我尝试在“ PHONE =”周围加上否定字符,但是没有运气。 I can get the phone number in its own group, but that doesn't help when assigning to the javascript var, which only cares what matches. 我可以在自己的组中获取电话号码,但这在分配给javascript var时无济于事,而javascript var只关心匹配的内容。

REGEX: 正则表达式:

/PHONE=([^,]*)/g

DATA: 数据:

3={STATE=, SSN=, STREET2=, STREET1=, PHONE=9878906756 , MIDDLENAME=, FIRSTNAME=Dexter, POSTALCODE=, DATEOFBIRTH=19650802, GENDER=0, CITY=, LASTNAME=Morgan 3 = {STATE =,SSN =,STREET2 =,STREET1 =, PHONE = 9878906756 ,MIDDLENAME =,FIRSTNAME = Dexter,POSTALCODE =,DATEOFBIRTH = 19650802,GENDER = 0,CITY =,LASTNAME = Morgan

The way you're doing it is right, you just have to get the value of the capture group rather than the value of the whole match: 正确的做法是,您只需要获取捕获组的值,而不是整个匹配的值即可:

var result = str.match(/PHONE=([^,]*)/); // Or result = /PHONE=([^,]*)/.exec(str);
if (result) {
    console.log(result[1]); // "9878906756"
}

In the array you get back from match , the first entry is the whole match, and then there are additional entries for each capture group. 在数组中,您从match返回,第一个条目是整个匹配,然后每个捕获组都有其他条目。

You also don't need the g flag. 您也不需要g标志。

只需使用dataAfterRegex.substring(6)取出前6个字符(即PHONE=部分)。

Try 尝试

var str = "3={STATE=, SSN=, STREET2=, STREET1=, PHONE=9878906756, MIDDLENAME=, FIRSTNAME=Dexter, POSTALCODE=, DATEOFBIRTH=19650802, GENDER=0, CITY=, LASTNAME=Morgan";

var ph = str.match(/PHONE\=\d+/)[0].slice(-10);

console.log(ph);

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

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