使用Java在字符串中搜索连字符

时间:2018-08-29 17:29:21

标签: java string hyphen

我试图在字符串-中查找连字符"TC 1 - TC 24"的出现。为此,我使用了

"TC 1 - TC 24".contains(" \\-")

但是上面的表达式不会返回true。我在做什么错了?

代码如下:

if("TC 1 - TC 24".contains(" \\- ") == true) {

   //print something
}

5 个答案:

答案 0 :(得分:1)

如果提供的字符串包含指定的char值序列,则Java中的

app.get('/request/:id',function(req,res){ const id = req.params.id; console.log(id); // should display 123 }); 关键字将返回true

因此,下面的字符串返回True,因为它包含连字符。但是,我们不能算数。连字符出现的次数。

Contains

我正在使用以下代码查找连字符:

if ("TC 1 - TC- 24".contains("-")) {
    System.out.println("It containes hyphen ");
}

答案 1 :(得分:0)

尝试一下:

if ("TC 1 - TC 24".contains("-")) {
   System.out.println("True");
} else {
   System.out.println("False");
}

如评论中所指出,.contains()的参数不是regex

  

包含(CharSequence s):   当且仅当此字符串包含指定的char值序列时,才返回true。

此外,它返回布尔结果,因此您无需再次将其与truefalse进行显式比较

答案 2 :(得分:0)

您可以使用类似的内容:

if ( yourString.matches("[\\p{Alnum} ]+ - [\\p{Alnum} ]+") )
{
    System.out.println("String contains a hyphen")
}

\\ p是字母数字的POSIX字符类

答案 3 :(得分:0)

您可以使用String类的 indexOf 方法,因为indexOf从给定的String中搜索字符串。 如果找到,它将返回该字符串的索引,否则将返回-1。 因此,您可以轻松使用 indexOf 。 我给了下面的代码,请仔细阅读。

public static void main(String[] args) {
    String hypen="12-35";
    int index = hypen.indexOf("-");
    if (index != -1) {
        System.out.println("True");
    } else {
        System.out.println("False");
    }
}

答案 4 :(得分:-1)

String str = "TC 1 - TC 24";

int str_length = str.length();
for (int i=0; i<str_length; i++) {
    char ch = str.charAt(i);
    if (ch == '-') {
        System.out.println("True");
        break;
    }
}