内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我需要一个包含特定单词的短语,然后如果它确实有那个单词,即使它是另一个单词的一部分,也要打印出整个单词。
我想如何找到这个词"apple"
,但我无法想象如何找到这个词"appletree"
。
到目前为止,我有一些代码可以找到单词apple并打印出来。
String phrase = "She's sitting under an appletree!";
if (phrase.contains("apple")) {
System.out.println("apple");
} else {
System.out.println("none");
}
我该如何打印"appletree"
?
您可以导入扫描仪以阅读该短语。您可以使用scanner.next()将每个输入标记捕获到一个String变量“s”中,在本例中为每个单词,然后使用if语句if(s.contains(“apple”))然后使用System.out .println(一个或多个)。
希望这可以帮助!
使用正则表达式为1-liner:
String target = phrase.replaceAll(".*?(\\w*apple\\w*).*", "$1");
这通过匹配(并因此替换)整个输入来工作,但是捕获目标然后使用反向引用($1
)到捕获的输入,导致仅返回目标。
其中字apple
出现使用匹配\\w*
在任一端(即,任意数量的字字符的)apple
。通过使用不情愿的量词.*?
,在目标之外匹配最小数量的前导字符,否则该表达式将一直匹配apple
,这将错过像这样的单词dapple
。
测试代码:
String phrase = "She's sitting under an appletree!";
String target = phrase.replaceAll(".*?(\\w*apple\\w*).*", "$1");
System.out.println(target);
输出:
appletree