[Regular Expressions] Find Groups of Characters, and ?:

We'll capture groups of characters we wish to match, use quantifiers with those groups, and use references to those groups in String.prototype.replace.

 

Let's see we have set of similar string starting with 'foo'

var str = `
  foobar
  fooboo
  foobaz
`;

 

And what we want to do is replace any 'foobar' & 'foobaz' with '**foobar**' && '**foobaz**' :

复制代码
var str = `
  foobar
  fooboo
  foobaz
`;

var regex = /foo(bar|baz)/g;

console.log(str.replace(regex, '**foo$1**'));

/*
"
  **foobar**
  fooboo
  **foobaz**
"
*/
复制代码

 

$1, capture the gourp and save into memory.

 

Another example:

Let's say we what to get the area code for each number. 

var str = `800-456-7890
(555) 456-7890
4564567890`;

 

So the result for the input should be '800, 555, 456'.

 

Todo this,

 

first: divide those number into xxx xxx xxxx, 3 3 4 group:

var regex = /\d{3}\d{3}\d{4}/g;

 

Second: now the only last one match, because, between group, there can be 'empty space' or  '-':

Use:

\s  // for space
-   // for -
[\s-]  // for select one element inside [], so \s or -
[\s-]? // 0 or more

SO:

var regex = /\d{3}[\s-]?\d{3}[\s-]?\d{4}/g;

 

 

Third: we need to match ():

\(?  // match (: can be 0 or 1
\)?  // match ) : can be 0 or 1

SO:

var regex = /\(?\d{3}\)?[\s-]?\d{3}[\s-]?\d{4}/g;

 

Last: we need to capture the first 3 digital number group. use  (xxx):

var regex = /\(?\(d{3})\)?[\s-]?\d{3}[\s-]?\d{4}/g;

 

then console.log the captured group:

console.log(str.replace(regex, 'area code: $1'))

/*

"area code: 800
area code: 555
area code: 456"
*/

 

Example 3:

re-format the number to xxx-xxx-xxxx:

复制代码
var str = `800-456-7890
(555) 456-7890
4564567890`;

var regex = /\(?(\d{3})\)?[\s-]?(\d{3})[\s-]?(\d{4})/g;
    
var res = str.replace(regex, "$1-$2-$3");

console.log(res);

/*
"800-456-7890
555-456-7890
456-456-7890"
*/
复制代码

 

 

------------------

As we said, (xx) actually capture the group value and store into the memory, if you don't store tha reference into the memory, you can do:

复制代码
(?:xxx) // ?: won't store the reference into the memory

console.log(str.replace(regex, 'area code: $1'))

/*
"area code: $1
area code: $1
area code: $1"
*/
复制代码

 

 

-----------------------------

 

-----------------

(^\d{2}\/\d{2}\/(?:2015|2016) (\d{2}:\d{2}$))

 

------------------------------

/((?:sword|flat|blow)fish)/gim

 

--------------

Grab Your Passports

/\d{9}\d([A-Z]{3})(\d{6})\d([a-z])\d{23}/gim

posted @   Zhentiw  阅读(256)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示