現在我有一個正則表達式,看起來像"\\w+ \\w+"
找到2個單詞的短語,但是,他們不重疊。例如,如果我的句子是The dog ran inside
,那麼當我需要顯示"The dog", "dog ran", "ran inside"
時,輸出將顯示"The dog", "ran inside"
。我知道有一種方法可以做到這一點,但我只是太新,不能使用正則表達式來知道如何做到這一點。如何找到與正則表達式重疊的單詞集?
謝謝!
現在我有一個正則表達式,看起來像"\\w+ \\w+"
找到2個單詞的短語,但是,他們不重疊。例如,如果我的句子是The dog ran inside
,那麼當我需要顯示"The dog", "dog ran", "ran inside"
時,輸出將顯示"The dog", "ran inside"
。我知道有一種方法可以做到這一點,但我只是太新,不能使用正則表達式來知道如何做到這一點。如何找到與正則表達式重疊的單詞集?
謝謝!
這不可能純粹與正則表達式,你不能匹配相同的字符兩次(「狗」不能在兩個單獨的組)。這樣的事情並不需要正則表達式的一切,你可以簡單地用空格分割字符串,並結合它,只要你喜歡:
>>> words = "The dog ran inside".split(" ")
>>> [" ".join(words[i:i+2]) for i in range(len(words)-1)]
['The dog', 'dog ran', 'ran inside']
如果不解決您的問題請提供關於究竟你」的詳細信息重新努力完成。
Java正則表達式具有前瞻斷言,所以當然這可以通過正則表達式來實現。 –
使用一個lookahead得到第二個單詞,將非lookahead與lookahead部分連接起來。
# This is Perl. The important bits:
#
# $1 is what the first parens captured.
# $2 is what the second parens captured.
# . is the concatenation operator (like Java's "+").
while (/(\w+)(?=(\s+\w+))/g) {
my $phrase = $1 . $2;
...
}
對不起,沒有足夠的Java,但這也應該很容易在Java中完成。
爲什麼不把這兩個單詞放在前瞻中,並且不需要額外的字符串連接? –
@Tim Pietzcker,我想可以使用lookbehind來實現'/(?<=^| \ s)(?=(\ w + \ s + \ w +))/ g',可以簡化爲不 - 等價的「/(?=(\ b \ w + \ s + \ w +))/ g' – ikegami
最簡單的(和大串更快)的方法是使用分裂:
final String[] arrStr = "The dog ran inside".split(" ");
for (int i = 0, n = arrStr.length - 1; i < n; i++) {
System.out.format("%s %s%n", arrStr[i], arrStr[i + 1]);
}
出把
The dog
dog ran
ran inside
用正則表達式沒有找到竅門
你可以這樣做帶向前看,一個捕捉組和一個文字邊界錨點:
Pattern regex = Pattern.compile("\\b(?=(\\w+ \\w+))");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group(1));
}
爲什麼正則表達式甚至在這裏需要?爲什麼不創建單詞列表並打印後續的所有單詞? – DhruvPathak
對不起,我應該指定我正在使用Java Matcher和Pattern對這個文檔進行排序。我不知道如何處理這些沒有正則表達式。 – rakoonise
如果可能,請發佈您的代碼 –