正则表达式不贪心就是贪婪 [英] Regular Expression nongreedy is greedy

查看:97
本文介绍了正则表达式不贪心就是贪婪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下文字

tooooooooooooon

根据我正在阅读的这本书,当?出现在任何量词之后时,它就变得不贪婪.

According to this book I'm reading, when the ? follows after any quantifier, it becomes non greedy.

我的正则表达式to*?n仍返回tooooooooooooon.

My regex to*?n is still returning tooooooooooooon.

它应该返回ton不是吗?

知道为什么吗?

推荐答案

正则表达式只能匹配实际存在的文本片段.

A regular expression can only match a fragment of text that actually exists.

因为子字符串"ton"在字符串中不存在,所以不能是匹配的结果.匹配项只会返回原始字符串的子字符串

Because the substring 'ton' doesn't exist anywhere in your string, it can't be the result of a match. A match will only return a substring of the original string

要清楚,如果您使用下面的字符串,请加上一个额外的'n'

To be clear, if you were using the string below, with an extra 'n'

toooooooonoooooon

此正则表达式(不指定'o')

this regular expression (which doesn't specify 'o's)

t.*n

将匹配以下内容(在"n"之前尽可能多的字符)

would match the following (as many characters as possible before an 'n')

toooooooonoooooon

但是正则表达式

t.*?n

仅匹配以下内容(在"n"之前尽可能少的字符)

would only match the following (as few characters as possible before an 'n')

toooooooon

这篇关于正则表达式不贪心就是贪婪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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