[英]Javascript regex: is there a way to retrieve a string within a string with a prefix and a suffix?
I wanted to know if it was possible via regex to find a text within a string along with let's say 2 prefix chars and 2 suffix chars to the found string. 我想知道是否可以通过正则表达式在字符串中查找文本,以及对找到的字符串说2个前缀字符和2个后缀字符。 For example if we have this:
例如,如果我们有这个:
let longText = 'yo this is a foobar string man';
let textToFind = 'foobar';
// the result should be 'a foobar s'
Thanks! 谢谢!
Simply construct the regexp using the RegExp
constructor and using String#match
to get the desired match: 只需使用
RegExp
构造函数并使用String#match
来构造regexp即可获得所需的匹配项:
let longText = 'yo this is a foobar string man'; let textToFind = 'foobar'; let regex = new RegExp(`. ${textToFind} .`); console.log(longText.match(regex)[0]);
First the regex: 首先是正则表达式:
console.log('yo this is a foobar string man'.match('.{2}foobar.{2}'));
Secondly, this is basic stuff ... i would recommend you to read some tutorials of basic regex syntax, and start experimenting. 其次,这是基础知识。我建议您阅读一些有关正则表达式基本语法的教程,然后开始进行实验。 There are some nice online tools to help you along the way:
有一些不错的在线工具可以帮助您:
https://www.regextester.com https://www.regextester.com
https://www.debuggex.com https://www.debuggex.com
Also, besides the fact that nobody can read and understand its own regexes the next day, its a tool worth learning ;) 另外,除了第二天没人能阅读和理解自己的正则表达式外,它还是值得学习的工具;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.