正则表达式识别包含特定符号的字符串?

时间:2017-04-08 20:37:21

标签: java regex

我有一组输入+++,----,+ - + - 。在这些输入中,我希望字符串只包含+符号。

4 个答案:

答案 0 :(得分:2)

如果你想看一个字符串是否只包含+个字符,请写一个循环来检查它:

private static boolean containsOnly(String input, char ch) {
    if (input.isEmpty())
        return false;
    for (int i = 0; i < input.length(); i++)
        if (input.charAt(i) != ch)
            return false;
    return true;
}

然后调用它来检查:

System.out.println(containsOnly("++++", '+')); // prints: true
System.out.println(containsOnly("----", '+')); // prints: false
System.out.println(containsOnly("+-+-", '+')); // prints: false

<强>更新

如果必须使用正则表达式(性能更差),那么您可以执行以下任何操作:

// escape special character '+'
input.matches("\\++")

// '+' not special in a character class
input.matches("[+]+")

// if "+" is dynamic value at runtime, use quote() to escape for you,
// then use a repeating non-capturing group around that
input.matches("(?:" + Pattern.quote("+") + ")+")

如果空字符串应返回+,则将最终*替换为每个true

答案 1 :(得分:1)

用于检查字符串是否仅由一个重复符号组成的正则表达式是

^(.)\1*$

如果你只想要由'+'组成的行,那么它就是

如果您的正则表达式实现不支持^\++$(意思是“一个或多个”),请

^++*$+

答案 2 :(得分:0)

对于相同符号的序列,请使用

(.)\1+

作为正则表达式。例如,这将匹配+++---,但不匹配+--

答案 3 :(得分:0)

正则表达式模式:^[^\+]*?\+[^\+]*$

这只允许每个字符串加一个符号。

Demo Link

说明:

^         #From start of string
[^\+]*    #Match 0 or more non plus characters
\+        #Match 1 plus character
[^\+]*    #Match 0 or more non plus characters
$         #End of string

编辑,我只是​​阅读了问题下的评论,我实际上没有窃取评论的正则表达式(它恰好是智力收敛):

哎呀,使用匹配时忽略^和$ anchors。

input.matches("[^\\+]*?\+[^\\+]*")
相关问题