如何将模式与可选的引号匹配? [英] How do I match a pattern with optional surrounding quotes?

查看:132
本文介绍了如何将模式与可选的引号匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写与可以包含引号的模式匹配的正则表达式,但如果这样,则必须在开头和结尾都具有匹配的引号?

How would one write a regex that matches a pattern that can contain quotes, but if it does, must have matching quotes at the beginning and end?

"?(pattern)"?

将不起作用,因为它将允许以引号开头但不以引号结尾的模式.

Will not work because it will allow patterns that begin with a quote but don't end with one.

"(pattern)"|(pattern)

会起作用,但是是重复的.有没有一种更好的方法可以做到而又无需重复模式?

Will work, but is repetitive. Is there a better way to do that without repeating the pattern?

推荐答案

您可以通过使用反向引用条件:

/^(")?(pattern)(?(1)\1|)$/

比赛:

  • 模式
  • 模式"

不匹配:

  • 模式
  • 模式"

但是,这种模式有些复杂.它首先查找可选的引号,如果找到,则将其放入反向引用1.然后搜索您的模式.然后,它使用条件语法说如果再次找到后向引用1,则匹配它,否则不匹配".整个模式是锚定的(这意味着它需要自己显示在一行上)这样就不会捕获不匹配的引号(否则pattern"中的pattern将匹配).

This pattern is somewhat complex, however. It first looks for an optional quote, and puts it into backreference 1 if one is found. Then it searches for your pattern. Then it uses conditional syntax to say "if backreference 1 is found again, match it, otherwise match nothing". The whole pattern is anchored (which means that it needs to appear by itself on a line) so that unmatched quotes won't be captured (otherwise the pattern in pattern" would match).

请注意,对条件的支持因引擎而异,更详细但重复的表达式将得到更广泛的支持(并且可能更易于理解).

Note that support for conditionals varies by engine and the more verbose but repetitive expressions will be more widely supported (and likely easier to understand).

更新:此正则表达式的简单得多的版本是/^(")?(pattern)\1$/,它不需要有条件的.最初进行测试时,我所使用的测试仪给我一个假阴性,这使我不喜欢它(哎呀!).

Update: A much simpler version of this regex would be /^(")?(pattern)\1$/, which does not need a conditional. When I was testing this initially, the tester I was using gave me a false negative, which lead me to discount it (oops!).

我将为解决方案保留后代和兴趣,但这是一个更简单的版本,更可能在更广泛的引擎中使用(反向引用是此处使用的唯一功能,可能不受支持)

I'll leave the solution with the conditional up for posterity and interest, but this is a simpler version that is more likely to work in a wider variety of engines (backreferences are the only feature being used here which might be unsupported).

这篇关于如何将模式与可选的引号匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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