匹配两个不同令牌之间的任何字符串 [英] Match any string between two different tokens
问题描述
我正在尝试在两个不同的标记之间匹配字符串的一部分.它们可能是字符串中多次出现的标记.
I'm trying to match a part of a string between two different tokens. They might be multiple occurrences of the tokens in a string.
示例文本(标记为斜体,匹配的文本为粗体):
Sample text (tokens are italic, text to match is bold):
这是[begin-match] 示例文本 [end-match][begin-match] 标记和正常 [end-match] 文本.
我有以下正则表达式,如果令牌是 { 和 },它会起作用:
I have the following regex, which would work if the tokens were { and }:
/{([^}]+)}/g
我无法使用 [begin-match] 和 [end-match] 标记.看来Javascript中缺少负面的lookbehind是一个很大的损失.
I can't get this to work the [begin-match] and [end-match] tokens. It seems that the lack of negative lookbehind in Javascript is a big loss.
我不知道如何用 { 和 } 代替标记 [begin-match] 和 [结束比赛].我如何匹配这些?
I can't figure out how to substitute the { and } for the tokens [begin-match] and [end-match]. How can I match on those?
推荐答案
/x(.*?)y/g
其中 x
是开始标记和 y
结束标记.
/x(.*?)y/g
where x
is the beginning token and y
the ending token.
这个正则表达式的意思是:匹配任何东西(.
),任意次数(*
),尽可能少(?
).
This RegEx means: match anything (.
), any number of times (*
), as few times as possible (?
).
你的问题的一个直接例子是:
A direct example from your question would be:
/\[begin-match\](.*?)\[end-match\]/g
示例文本现在位于第一个捕获组中.
The sample text is now in the first capturing group.
这篇关于匹配两个不同令牌之间的任何字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!