如何获取整个单词使用子字符串? [英] how to get the whole words use substring?

查看:34
本文介绍了如何获取整个单词使用子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字符串 String fulltext = "我想创建一些文本,但我不知道 creater34r3 是什么,";

我有子字符串 String subtext = "create s";"create som""create so"..

如何获取subtext 的完整单词?(在本例中为create some"或create")

Pattern.compile("\\b(" + subtext + "\\p{Alnum}+)"); - 不工作 =(

解决方案

它可以工作,但是您应该使用 Matcher.find()(它会找到第一次出现的正则表达式)而不是 Matcher.matches()(针对整个字符串测试正则表达式).

Matcher m = Pattern.compile("\\b(" + subtext + "\\p{Alnum}*)").matcher(fulltext);System.out.println(m.find());System.out.println(m.group(1));

印刷品

真创造一些

正如 Sean Landsman 所指出的,它应该是 \\p{Alnum}*(因为潜台词可能出现在字符串的末尾,如果 + 使用了量词).

I have string String fulltext = "I would like to create some text and i dont know what creater34r3, ";

and i have substring String subtext = "create s"; or "create som" or "create so"..

how to get the whole words for subtext ? (in this case "create some" or "create")

Pattern.compile("\\b(" + subtext + "\\p{Alnum}+)"); - not work =(

解决方案

It works, but you should use Matcher.find() (which finds the first occurrence of the regex) instead of Matcher.matches() (which tests the regexp against the whole string).

Matcher m = Pattern.compile("\\b(" + subtext + "\\p{Alnum}*)").matcher(fulltext);
System.out.println(m.find());
System.out.println(m.group(1));

Prints

true
create some

Edit: as Sean Landsman pointed, it should be \\p{Alnum}* (because subtext may occur at the end of the string, and would not be matched if a + quantifier were used).

这篇关于如何获取整个单词使用子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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