Java 正则表达式某些字符可以存在或不存在,但之后什么都没有

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20255285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:37:00  来源:igfitidea点击:

regex certain character can exist or not but nothing after that

javajavascriptregex

提问by mysticfalls

I'm new to regex and I'm trying to do a search on a couple of string.

我是 regex 的新手,我正在尝试对几个字符串进行搜索。

I wanted to check if a certain character, in this case its ":" (without the quote) exist on the strings.

我想检查字符串中是否存在某个字符,在这种情况下是它的“:”(不带引号)。

If : does not exist in the string it would still match, but if : exist there should be nothing after that only space and new line will be allowed.

如果 : 不存在于字符串中,它仍然会匹配,但如果 : 存在,则之后应该没有任何内容,只允许空格和新行。

I have this pattern, but it does not seem to work as I want it.

我有这个模式,但它似乎并没有像我想要的那样工作。

(.*)(:?\s*\n*)

Thank you.

谢谢你。

采纳答案by Vector Gorgoth

If I understand your question correctly, ^[^:]*(:\s*)?$

如果我正确理解你的问题, ^[^:]*(:\s*)?$

Let's break this down a bit:

让我们把它分解一下:

^Starting anchor; without this, the match can restart itself every time it sees another colon, or non-whitespace following a colon.

^启动锚;如果没有这个,匹配可以在每次看到另一个冒号或冒号后面的非空白时重新启动。

[^:]*Match any number of characters that AREN'T colon characters; this way, if the entire string is non-colon characters, the string is treated as a valid match.

[^:]*匹配任意数量的非冒号字符;这样,如果整个字符串都是非冒号字符,则该字符串将被视为有效匹配。

(:\s*)?If at any point we dosee a colon, all following characters must be white space until the end of the string; the grouping parens and following ?act to make this an all-or-nothing conditional statement.

(:\s*)?如果在任何时候我们确实看到了一个冒号,那么所有后面的字符必须是空格,直到字符串的末尾;分组括号和以下?行为使其成为全有或全无的条件语句。

$Ending anchor; without this, the regex won't know that if it sees a colon the following whitespace MUST persist until the end of the string.

$结束锚;没有这个,正则表达式不会知道如果它看到一个冒号,后面的空格必须持续到字符串的末尾。

回答by arnaudbey

here is a pattern which should work

这是一个应该工作的模式

/^([^:]*|([^:]*:\s*))$/

you can use the pipe to manage alternatives

您可以使用管道来管理替代品