简体   繁体   English

如何用 JavaScript 中的正则表达式捕获组替换整个字符串?

[英]How to replace entire string with Regex capture groups in JavaScript?

In a NodeJS application, I have a phone number field in my data that displays any number of phone numbers, one after another, in the same string:在 NodeJS 应用程序中,我的数据中有一个电话号码字段,它在同一字符串中一个接一个地显示任意数量的电话号码:

\n\n \n (555) 555-5555 (Main)\n\n, \n\n \n (777) 777-777 (Domestic Fax)\n\n

I want to extract only the 'Main' phone number and convert it to the format 555-555-5555 , that is whatever the Main number is.我只想提取“主”电话号码并将其转换为格式555-555-5555 ,即主号码是什么。 Basically I just want to extract whatever number precedes 'Main' and make it more legible (replacing the space with the '-')基本上我只想提取'Main'之前的任何数字并使其更清晰(用'-'替换空格)

I got as far as finding the correct regex string我已经找到了正确的正则表达式字符串

const phoneRegex = /^[ \\n]*\(([0-9]{3})\)( )([0-9]{3}-[0-9]{4}) \(Main\).*$/

but when I try to replace the string, it doesn't work但是当我尝试替换字符串时,它不起作用

foo.phone =foo.phone.replace(phoneRegex,'$1-$3')

I keep getting the entire matched portion -- that is all the \n's and everything up to and including '(Main)'我不断得到整个匹配的部分——那是所有的 \n 以及直到并包括 '(Main)' 的所有内容

I have searched for how to replace the entire string with the capture groups, but I haven't figured it out.我已经搜索了如何用捕获组替换整个字符串,但我还没有弄清楚。

Would that work for you?这对你有用吗?

 const str = `\n\n \n (555) 555-5555 (Main)\n\n, \n\n \n (777) 777-777 (Domestic Fax)\n\n`, [,code, phone] = str.match(/\((\d{3})\)\s(\d{3}\-\d{4})\s\(Main\)/), result = `${code}-${phone}` console.log(result)

You may use您可以使用

 var s = "\\n\\n \\n (555) 555-5555 (Main)\\n\\n, \\n\\n \\n (777) 777-777 (Domestic Fax)\\n\\n"; console.log( s.replace(/^[^]*?\((\d{3})\)\s*(\d+)-(\d+)\s*\(Main\)[^]*/, '$1-$2-$3') );

Details细节

  • ^ - start of string ^ - 字符串的开头
  • [^]*? - any 0 or more chars, as few as possible - 任何 0 个或更多字符,尽可能少
  • \( - a ( \( - 一个(
  • (\d{3}) - Group 1: three digits (\d{3}) - 第 1 组:三位数字
  • \) - a ) char \) - a )字符
  • \s* - 0+ whitespaces \s* - 0+ 个空格
  • (\d+) - Group 2: one or more digits (\d+) - 第 2 组:一位或多位数字
  • - - a hyphen - - 一个连字符
  • (\d+) - Group 3: one or more digits (\d+) - 第 3 组:一位或多位数字
  • \s* - 0+ whitespaces \s* - 0+ 个空格
  • \(Main\) - a (Main) string \(Main\) - 一个(Main)字符串
  • [^]* - the rest of the string. [^]* - 字符串的 rest。

See the regex demo .请参阅正则表达式演示

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

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