本文介绍了我的正则表达式匹配太多了.我怎样才能告诉它匹配最小的可能模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个正则表达式:

('.+')

它必须像在 C 中一样匹配字符文字.例如,如果我有 'a' b 'a' 它应该匹配 a 和 '在他们周围.

It has to match character literals like in C. For example, if I have 'a' b 'a' it should match the a's and the ''s around them.

然而,它也匹配b(它不应该),可能是因为严格来说它也在'之间.

However, it also matches the b also (it should not), probably because it is, strictly speaking, also between ''s.

这是错误原因的屏幕截图(我用它来突出显示语法):

Here is a screenshot of how it goes wrong (I use this for syntax highlighting):

我对正则表达式还很陌生.我怎么能告诉正则表达式不匹配这个?

I'm fairly new to regular expressions. How can I tell the regex not to match this?

推荐答案

它是贪婪的,匹配第一个撇号和最后一个撇号以及两者之间的所有内容.

It is being greedy and matching the first apostrophe and the last one and everything in between.

这应该匹配任何不是撇号的东西.

This should match anything that isn't an apostrophe.

('[^']+')

另一种选择是尝试非贪婪匹配.

Another alternative is to try non-greedy matches.

('.+?')

这篇关于我的正则表达式匹配太多了.我怎样才能告诉它匹配最小的可能模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 05:48