在字符串Java中找到完整的单词 [英] Find a complete word in a string java

查看:54
本文介绍了在字符串Java中找到完整的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一段代码,例如,如果我有

I am writing a piece of code in which i have to find only complete words for example if i have

String str = "today is tuesday";

并且我正在搜索"t",那么我应该找不到任何单词.

and I'm searching for "t" then I should not find any word.

有人可以告诉我如何用Java编写这样的程序吗?

Can anybody tell how can I write such a program in java?

推荐答案

我将正则表达式用于此类任务.在您的情况下,它应该看起来像这样:

I use a regexps for such tasks. In your case it should look something like this:

String str = "today is tuesday";
return str.matches(".*?\\bt\\b.*?"); // returns "false"

String str = "today is t uesday";
return str.matches(".*?\\bt\\b.*?"); // returns "true"

简短说明:

.匹配任何字符,*?是零次或多次,\ b是单词边界.

. matches any character, *? is for zero or more times, \b is a word boundary.

有关正则表达式的更多信息,请参见此处或专门针对Java

More information on regexps can be found here or specifically for java here

这篇关于在字符串Java中找到完整的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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