string.matches(regex)返回false,尽管我认为应该为true [英] string.matches(regex) returns false, although I think it should be true

查看:383
本文介绍了string.matches(regex)返回false,尽管我认为应该为true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java正则表达式.

I am working with Java regular expressions.

哦,我真的很想念Perl !! Java正则表达式是如此困难.

Oh, I really miss Perl!! Java regular expressions are so hard.

无论如何,下面是我的代码.

Anyway, below is my code.

oneLine = "{\"kind\":\"list\",\"items\"";
System.out.println(oneLine.matches("kind"));

我希望屏幕上显示"true",但我只能看到"false".

I expected "true" to be shown on the screen, but I could only see "false".

代码有什么问题?我该如何解决?

What's wrong with the code? And how can I fix it?

先谢谢您!

推荐答案

String#matches() takes a regex as parameter, in which anchors are implicit. So, your regex pattern will be matched at the beginning till the end of the string.

由于您的字符串不是以"kind"开头,因此它将返回false.

Since your string does not start with "kind", so it returns false.

现在,根据您当前的问题,我认为您无需在此处使用regex.只需使用 String#contains() 方法可以正常工作:-

Now, as per your current problem, I think you don't need to use regex here. Simply using String#contains() method will work fine: -

oneLine.contains("kind");

或者,如果要使用matches,则构建正则表达式以匹配完整的字符串:-

Or, if you want to use matches, then build the regex to match complete string: -

oneLine.matches(".*kind.*");

这篇关于string.matches(regex)返回false,尽管我认为应该为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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