我有一个字符串和一个模式
myString = "thiS is testing my patience with regexIs";
pattern = "is";
我想遍历 myString 并打印包含该模式的每个单词。我的梦想输出(对大小写不敏感)是
"thiS is regexIs"
我知道我会遍历长度为 myString 的字符串,但我想不出任何在这种情况下有意义的字符串方法。我之前计算过出现次数(使用诸如 charAt(i)、匹配、包含、replaceAll 之类的东西),并找到了模式、索引位置、特殊字符、数字等。我在真正的字符串方法的前两周用法,但到目前为止我学到的东西我无法拼凑起来解决这个难题。
最佳答案
以下方法 findMatches()
返回输入句子中匹配单词的 List
。您可以使用它来获取匹配项,然后在需要的地方打印出来。
List<String> findMatches(String input, String pattern) {
String[] parts = input.split(" ");
List<String> words = new ArrayList<String>();
for (String part : parts) {
if (part.toLowerCase().contains(pattern.toLowerCase())) {
words.add(part);
}
}
return words;
}
用法:
String myString = "thiS is testing my patience with regexIs";
String pattern = "is";
List<String> matches = findMatches(myString, pattern);
for (String match : matches) {
System.out.println(match + " ");
}
关于java - 使用正则表达式/字符串方法 : Print Words containing Pattern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35717849/