如何提取“零件"根据某些 RegExp 模式的字符串? [英] How to extract "parts" of a String according to some RegExp pattern?
本文介绍了如何提取“零件"根据某些 RegExp 模式的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 JavaScript 中,给定一个正则表达式模式和一个字符串:
In JavaScript, given a regexp pattern and a string:
var pattern = '/this/[0-9a-zA-Z]+/that/[0-9a-zA-Z]+';
var str = '/this/12/that/34';
如何返回包含以下内容的数组:
How to return an array containing:
['12', '34']
以下匹配整个输入字符串,从而将其作为一个整体返回.
The following matches the whole input string and thus returns it as a whole.
var res1 = '/this/12/that/34'.match(/\/this\/[0-9a-zA-Z]+\/that\/[0-9a-zA-Z]+/));
以下匹配输入字符串的所有部分".
The following matches all "parts" of the input string.
var res2 = '/this/12/that/34'.match(/[0-9a-zA-Z]+/g));
推荐答案
使用捕获组:
var res1 = '/this/12/that/34'.match(/\/this\/([0-9a-zA-Z]+)\/that\/([0-9a-zA-Z]+)/);
你会得到一个包含 3 个元素的数组:
You will get an array containing 3 elements:
整场比赛;
The whole match;
12
34
并且您可以使用 .slice(1)
删除第一个元素:
And you can use .slice(1)
to remove the first element:
var res1 = '/this/12/that/34'.match(/\/this\/([0-9a-zA-Z]+)\/that\/([0-9a-zA-Z]+)/).slice(1);
这篇关于如何提取“零件"根据某些 RegExp 模式的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文