正则表达式,忽略模式(如果用引号引起来) [英] Regex, ignoring pattern if it's in quotes

查看:128
本文介绍了正则表达式,忽略模式(如果用引号引起来)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为学校项目的一部分,编写一个非常简单的脚本解析器,虽然这不是必需的,但我很好奇能否仅使用一个正则表达式来完成它.

Writing a very simple script parser as part of a school project, and while it's not required I'm curious if it can be done with only a regular expression.

语法类似于ASP,其中脚本以<%开头,以%>结尾.

The syntax is similar to ASP, where a script begins with <% and ends with %>.

它仅支持一个命令"pr",与echo或Response.Write相同.

It only supports one command "pr", which is the same as echo or Response.Write.

现在我正在使用此正则表达式查找脚本块:

Right now I'm using this regular expression to find script blocks:

(<%\s*([\s\S]*?)\s*%>)

但是如果我有这样的命令:

But if I have a command like this:

<% pr "%>"; %>

...它显然只匹配:

...it obviously only matches:

<% pr "%>

有没有一种方法可以使用纯正则表达式来忽略引号内的结束标记?我主要担心的是,如果这样的话,它可能会匹配引号之间但实际上不在引号之间的标签.例如...

Is there a way using pure regex to to ignore closing tags that are within quotes? My main worry is that it might match tags that are between quotes, but actually outside of them, if that makes sense. For example...

<% pr "hello world"; %> "

从技术上说,结束标记用引号引起来,但是它不是在打开"然后关闭"引号内,而是相反.

Technically the closing tag is surrounded by quotes, but it's not inside an "open" then "close" quote, rather the other way around.

如果用正则表达式可以做到这一点很整洁,否则我怀疑如果我想支持此功能,我将不得不手动遍历传入的文本并自己解析出这些块,这实际上也没什么大不了的

If this is possible with regex that would be pretty neat, otherwise I suspect that if I wanted to support this functionality I would have to manually iterate through the incoming text and parse the blocks out myself, which is no big deal really either.

谢谢!

推荐答案

我认为这应该适合您的需求:<%(".*?"|.*?)*?%>(请参见

I think this one should suit your needs: <%(".*?"|.*?)*?%> (see the Demo).

说明:

.*尽可能匹配 ,而.*?尽可能匹配 .

While .* matches as long as possible, .*? matches as little as possible.

例如(使用伪代码)

"#foo# #bar#".matches(/#(.*)#/).group(1) // will return ["foo# #bar"]

同时

"#foo# #bar#".matches(/#(.*?)#/).group(1) // will return ["foo", "bar"]

这篇关于正则表达式,忽略模式(如果用引号引起来)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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