简体   繁体   English

正则表达式用于多个字符实例

[英]Regex for multiple instances of character

In Java, using a regular expression, how would I check a string to see if it had a correct amount of instances of a character. 在Java中,使用正则表达式,我将如何检查字符串以查看它是否具有正确数量的字符实例。

For example take the string hello.world.hello:world: . 例如,使用字符串hello.world.hello:world: How could this string be checked to see if it contained two instances of a . 如何检查此字符串以查看是否包含的两个实例. or two instances of a : ? 或两个实例:

I have tried 我努力了

Pattern p = Pattern.compile("[:]{2}");
Matcher m = p.matcher(hello.world.hello:world:);
m.find();

but that failed. 但这失败了。

Edit 编辑

First I would like to say thank you for all the answers. 首先,我想感谢您的所有回答。 I noticed a lot of the answers said something along the lines of "This means: zero or more non-colons, followed by a single colon, followed by zero or more non-colons - matched exactly twice ". 我注意到很多答案都说“这意味着: zero or more non-colons, followed by a single colon, followed by zero or more non-colons - matched exactly twice ”。 So if you were checking for 3 : in a string such as Hello::World: how would you do it? 所以,如果你对3人检查:在一个字符串,如Hello::World:你会怎么做呢?

Well, using matches you could use: 好吧,使用matches您可以使用:

"([^:]*:[^:]*){2}"

This means: "zero or more non-colons, followed by a single colon, followed by zero or more non-colons - matched exactly twice". 这意味着:“零个或多个非冒号,后接一个冒号,后跟零个或多个非冒号-精确匹配两次”。

Using find is not as good, as there may be additional : and it will just ignore them. 使用find并不是很好,因为可能还有其他: ,它只会忽略它们。

You can use this regex based on two lookaheads assertions: 您可以基于两个先行断言使用此正则表达式:

^(?=(?:[^.]*\.){2}[^.]*$)(?=(?:[^:]*:){2}[^:]*$)

(?=(?:[^.]*\\.){2}[^.]*$) makes sure there are exactly 2 DOTS and (?=(?:[^:]*:){2}[^:]*$) asserts that there are exactly 2 colons in input string. (?=(?:[^.]*\\.){2}[^.]*$)确保有2个DOTS和(?=(?:[^:]*:){2}[^:]*$)断言输入字符串中恰好有2个冒号。

RegEx Demo 正则演示

You can determine whether the string has exectly the given number of a certain character, say ':' , by attempting to match it against a pattern of this form: 您可以通过尝试将字符串与以下形式的模式匹配来确定字符串是否正好具有给定数目的某个字符,例如':'

^(?:[^:]*[:]){2}[^:]*$

That says exactly two non-capturing groups consisting of any number (including zero) of characters other than ':' followed by one colon, with the second group followed by any number of additional characters other than ':' . 也就是说,恰好有两个非捕获组,由除':'以外的任意数量(包括零个)的字符组成,后跟一个冒号,第二组后面跟着除':'之外的任意数量的其他字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM