我有字符串 String fulltext = "I would like to create some text and i don't know what 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));
打印
true
create some
编辑:正如 Sean Landsman 指出的那样,它应该是 \\p{Alnum}*
(因为子文本可能出现在字符串的末尾,如果 +
使用了量词)。
关于java - 如何让整个单词使用子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15138738/