匹配两个不同令牌之间的任何字符串 [英] Match any string between two different tokens

查看:41
本文介绍了匹配两个不同令牌之间的任何字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在两个不同的标记之间匹配字符串的一部分.它们可能是字符串中多次出现的标记.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆