Home > Web Front-end > JS Tutorial > Detailed explanation of using regular expressions to extract strings (with code)

Detailed explanation of using regular expressions to extract strings (with code)

php中世界最好的语言
Release: 2018-03-29 17:52:47
Original
3617 people have browsed it

这次给大家带来使用正则表达式提取字符串详解,使用正则表达式提取字符串的注意事项有哪些,下面就是实战案例,一起来看一下。

在JS的正则零宽断言匹配中,只支持前瞻匹配,不支持后瞻。这就尴尬了,因为在业务当中,我们大多时候是知道了要目标数据的前后缀字符串,但是并不想连同前后缀一起获取。

为了模拟后瞻,我想,要不就用笨方法,先将前后缀字符串一同提取,然后再讲前后缀字符串一同replace为空字符串。于是就有了下面这个简单的方法,但确实很实用:

示例代码如下

// 提取固定字符之间的字符串
function getInnerString(source, prefix, postfix) {
 var regexp = new RegExp(encodeReg(prefix) + '.+' + encodeReg(postfix), 'gi');
 var matches = String(source).match(regexp);
 var formatedMatches = _.map(matches, value => {
  return value
   .replace(prefix, '')
   .replace(postfix, '');
 });
 return formatedMatches;
}
//转义影响正则的字符
function encodeReg(source) {
 return String(source).replace(/([.*+?^=!:${}()|[\]/\\])/g,'\\$1');
}
Copy after login

使用:

var a = '让我们荡起双桨吧';
getInnerString(a, '让我们', '吧'); // ['双桨']
var b = '老总和不在办公室,有事请留言给李秘书';
getInnerString(b, '有事请留言给', ''); // ['李秘书']
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

容易产生错误的js手机号码验证

在php与JS里怎么用正则匹配汉字

The above is the detailed content of Detailed explanation of using regular expressions to extract strings (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template