正则表达式问号 [英] Regex question mark

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

问题描述

匹配具有以下模式的字符串:

To match a string with pattern like:

-TEXT-someMore-String

要获得 -TEXT - ,我才知道这有效:

To get -TEXT-, I came to know that this works:

/-(.+?)-/ // -TEXT-

据我所知,将前面的令牌视为可选项,如下所示:

As of what I know, ? makes preceding token as optional as in:

colou?r 匹配颜色颜色

我最初使用正则表达式来获取 -TEXT - 这样的部分:

I initially put in regex to get -TEXT- part like this:

/-(.+)-/

但它给了 -TEXT-someMore -

如何添加停止正则表达式获取 -TEXT - 部分正确吗?因为它曾经使前面的令牌可选不在某些点停止,如上例所示?

How does adding ? stops regex to get the -TEXT- part correctly? Since it used to make preceding token optional not stopping at certain point like in above example ?

推荐答案

如你所说,有时意味着零或一,但在你的正则表达式 +?是一个单位,意思是一个或多个—和最好尽可能少。 (这与裸 + 相反,这意味着一个或多个—并且最好尽可能多。)

As you say, ? sometimes means "zero or one", but in your regex +? is a single unit meaning "one or more — and preferably as few as possible". (This is in contrast to bare +, which means "one or more — and preferably as many as possible".)

正如文档所说:


但是,如果量词后跟一个问号,
那么它变得懒惰,而是匹配最小
次数,所以模式 / \ *。*?\ * /
使用C注释做正确的事情。
各种量词的含义并没有改变,只是首选的
数量的匹配。不要将
问号的使用与其本身作为量词的使用混淆。
因为它有两种用途,它有时会出现加倍,因为 \d ?? \d 中的
,它按首选项匹配一位数,但是如果
匹配两个,这是模式其余部分匹配的唯一方式。

However, if a quantifier is followed by a question mark, then it becomes lazy, and instead matches the minimum number of times possible, so the pattern /\*.*?\*/ does the right thing with the C comments. The meaning of the various quantifiers is not otherwise changed, just the preferred number of matches. Do not confuse this use of question mark with its use as a quantifier in its own right. Because it has two uses, it can sometimes appear doubled, as in \d??\d which matches one digit by preference, but can match two if that is the only way the rest of the pattern matches.

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

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