正则表达式匹配具有偶数个引号的字符串 [英] Regex to match a string with an even number of quotes

查看:58
本文介绍了正则表达式匹配具有偶数个引号的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想出了:([^"]*["][^"]*["][^"]*)*

它适用于所有情况,除了针对空字符串.我认为它会起作用,因为最后一颗星与前一个标记匹配次或更多次.

It works in all cases except against the empty string. I thought it would work because the last star matches the previous token zero or more times.

有什么想法吗?

另外,如果有更好的方法,请告诉我并详细解释.

Also if there's a much better way of doing this please let me know and explain it in detail.

解决方案必须是正则表达式,因为它将被使用的地方是一个需要正则表达式的钩子.

它还必须匹配不带引号的字符串,因为零是偶数

推荐答案

你的正则表达式应该匹配完全空的字符串,但不匹配例如由单个空格组成的字符串,因为您的正则表达式声明如果该字符串不是完全空,则它需要至少包含一个双引号.这是因为正则表达式中的 ["] 标记后面没有 *.

your regex should match the completely empty string, but not e.g. a string consisting of a single space, because your regex states that if the string is not completely empty, it needs to contain at least one double quote. This is because of the ["] tokens inside the regex which are not followed by *.

考虑所需正则表达式的正确方法如下:您要匹配(不带双引号的字符串)后跟(双引号)加(不带双引号的字符串)后跟(双)引号后跟(字符串没有双引号),然后从第一个后继"开始无限重复.没有双引号的字符串是 [^"]*,所以你得到(为了可读性添加了空格):

The proper way to think about the needed regular expression is as follows: you want to match (string without double quotes) followed by (double quote) plus (string without double quotes) followed by (double) quote followed by (string without double quotes), and then repeat starting from the first 'followed by' ad infinitum. String without double quotes is [^"]*, so you get (whitespace added for readability):

[^"]* (" [^"]* " [^"]*)*

如果您将其与正则表达式进行比较,第一个 [^"]* 已移出重复.

If you compare this with your regular expression, the first [^"]* has been moved out of the repetition.

这篇关于正则表达式匹配具有偶数个引号的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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