Javascript Regex-提取方括号标记之间的字符串
我有一些字符串中的标记,比如Javascript Regex-提取方括号标记之间的字符串,javascript,php,regex,Javascript,Php,Regex,我有一些字符串中的标记,比如[note]some text[/note],我想从中提取标记之间的内部文本 示例文本: Want to extract data [note]This is the text I want to extract[/note] but this is not only tag [note]Another text I want to [text:sample] extract[/note]. Can you do it? 从给定文本中,提取以下内容: 这是我要提
[note]some text[/note]
,我想从中提取标记之间的内部文本
示例文本:
Want to extract data [note]This is the text I want to extract[/note]
but this is not only tag [note]Another text I want to [text:sample]
extract[/note]. Can you do it?
从给定文本中,提取以下内容:
这是我要提取的文本
我想[text:sample]提取的另一个文本
我们可以尝试使用以下正则表达式模式进行匹配:
\[note\]([\s\S]*?)\[\/note\]
这意味着只需捕获介于[note]
和最近的结束标记[/note]
之间的任何内容。请注意,如果有必要,我们使用[\s\s]*
在换行符中潜在地匹配所需的内容
var re=/\[note\]([\s\s]*?)\[\/note\]/g;
var s='想要提取数据[note]这是我想要提取的文本[/note]\n但这不仅仅是标记[note]我想要提取的另一文本[text:sample]\n extract[/note]。你能做到吗;
var-m;
做{
m=执行董事;
如果(m){
console.log(m[1]);
}
}while(m)代码>我在Tim发布他的答案时写了这篇文章,这很像,但我想我还是会发布它,因为它被提取到一个可用于任何标记的可重用函数中
const str = `Want to extract data [note]This is the text I want to extract[/note]
but this is not only tag [note]Another text I want to [text:sample]
extract[/note]. Can you do it?`;
function extractTagContent(tag, str) {
const re = new RegExp(`\\[${tag}\\](.*?)\\[\\/${tag}\\]`, "igs");
const matches = [];
let found;
while ((found = re.exec(str)) !== null) {
matches.push(found[1]);
}
return matches;
}
const content = extractTagContent("note", str);
// content now has:
// ['This is the text I want to extract', 'Another text I want to [text:sample] extract. Can you do it?']
演示: