任何人都可以解释吗?:在正则表达式中 [英] Can Anyone Explain ?: in regular expression

查看:44
本文介绍了任何人都可以解释吗?:在正则表达式中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TCL:谁能解释一下?:在正则表达式中

TCL: Can Anyone Explain ?: in regular expression

我在 ?和?:.

?表示前面的字符可能存在也可能不存在.

? means preceding character may or may not be present.

然后我不明白 (?:) 表示什么.

Then I am not understanding what (?:) indicates.

谁能解释一下.

([0-9]+(?:\.[0-9]*)?)

推荐答案

假设,您试图在输入字符串中查找类似 ABC123ABC123.45 的内容并且您想分别捕获字母和数字.你会使用像

Suppose, you were trying to look for something like ABC123 or ABC123.45 in your input String and you wanted to capture the letters and the numbers separately. You would use a regex (a bit similar to yours) like

([A-Z]+)([0-9]+(\.[0-9]+)?)

上述正则表达式将匹配 ABC123.45 并提供三个组,代表整个匹配的子部分,并由您放置这些 () 的位置决定括号.因此,鉴于我们的正则表达式(不使用 ?:),我们得到了

The above regex would match ABC123.45 and provide three groups as well that represent sub-parts of the whole match and are decided by where you put those () brackets. So, given our regex (without using ?:) we got

Group 1 = ABC
Group 2 = 123.45
Group 3 = .45

现在,始终捕获小数部分可能没有多大意义,实际上它也已在我们的第 2 组中捕获.那么,如何使该组 () 不被捕获?是的,通过在开头使用 ?: 作为

Now, it may not make much sense to capture the decimal portion always and it actually has already been captured in our Group 2 as well. So, how would you make that group () non capturing? Yes, by using ?: at the start as

([A-Z]+)([0-9]+(?:\.[0-9]+)?)

现在,你只能得到两个想要的组

Now, you only get the two desired groups

Group 1 = ABC
Group 2 = 123.45

注意,我还将正则表达式的最后一部分从 \.[0-9]* 更改为 \.[0-9]+.这将阻止 123. 上的匹配,即没有小数部分但仍有点的数字.

Notice, I also changed the last part of the regex from \.[0-9]* to \.[0-9]+. This would prevent a match on 123. i.e. numbers without a decimal part but still having a dot.

这篇关于任何人都可以解释吗?:在正则表达式中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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