たとえば、検索文字列に基づいて単語(つまり、前後の空白を意味します)を検索したいと思います。
String s = "sdaaf fd hgfaaf ghjfada dgffaasdf";
文字列を含むすべての単語を検索したいのですが"aa"
、答えは次の単語になります。
"sdaaf" , "hgfaaf" , "dgffaasdf"
より直接的な方法があるため、正規表現を使用してこの問題を解決することはできません。
String phrase = "aa";
String s = "sdaaf fd hgfaaf ghjfada dgffaasdf";
String[] words = s.split(" ");
List<String> wordList = new ArrayList<String>();
for(String word : words)
{
if(word.contains(phrase))
{
wordList.add(word);
}
]
String regex = "(\\w+aaa\\w+)+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher("helaaalo woraaald how are you toaaaday");
while (matcher.find()) {
System.out.print(matcher.group() + " ");
}
出力は次のとおりです。helaaalo woraaald toaaaday
ニーズに合わせてパターンを変更できます。
次の手順を順番に実行して、次のすべての単語を取得します"aa"
:-
文字列をスペースで分割する-String#split
この目的にはメソッドを使用します。これにより、すべての要素がスペースで区切られた文字列配列が得られます。
次に、取得した文字列配列を繰り返し処理します。
要素ごとに、シーケンスが含まれているかどうかを確認します"aa"
-String#contains
この目的にはメソッドを使用します。
ArrayList
事前に作成する必要があるに追加することができます。これは、各単語に一致する正規表現を使用する完全なソリューションです。
final String input = "asdf ljh poiu ddaa aad aa", strToMatch = "aa";
final Matcher m = Pattern.compile(
String.format("\\w*?%s\\w*", Pattern.quote(strToMatch))).matcher(input);
while (m.find()) System.out.println(m.group());