最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - How to match a substring surrounded by known prefix and suffix in javascript - Stack Overflow

programmeradmin0浏览0评论

Given a string, such as:

example string with an intended nested string to match.

How to isolate a substring knowing only a prefix and suffix for it, e.g. between intended and to match?

Given a string, such as:

example string with an intended nested string to match.

How to isolate a substring knowing only a prefix and suffix for it, e.g. between intended and to match?

Share Improve this question asked May 9, 2013 at 22:54 Vincent ScheibVincent Scheib 18.6k11 gold badges62 silver badges80 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 14

Use regular expressions with non-capturing parentheses, like so:

string = 'example string with an intended nested string to match.';
regexp = /(?:intended)(.*)(?:to match)/;
firstMatch = regexp.exec(string)[1]; // " nested string "

The question mark has several uses in regular expressions, the parentheses question mark colon form (?:more regex) is the non-capturing parentheses.

See MDN for more details of exec(), string.match(), and regular expressions.

Look behind (?<=...) and look ahead (?=...) can be used to the same effect -- they are used to match but are not included in the result, the term for that behavior is referred to as "not consuming"

RegExp Lookahead Lookbehind

/(?<=intended).+(?=to match)/g;

RegEx101

const str = `example string with an intended nested string to match.`;

const rgx = /(?<=intended).+(?=to match)/g;

const hit = str.match(rgx);

console.log(hit[0]);

发布评论

评论列表(0)

  1. 暂无评论