Home > Web Front-end > JS Tutorial > body text

Use regular expressions to extract strings between fixed characters_regular expressions

微波
Release: 2017-06-28 13:45:46
Original
2526 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

总结

The above is the detailed content of Use regular expressions to extract strings between fixed characters_regular expressions. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!