![](/img/trans.png)
[英]Using regex to split sentence into tokens stripping it of all the necessary punctuation excluding punctuation that is part of a word
[英]regex last word in a sentence ending with punctuation (period)
我正在尋找正則表達式模式,而不是Java代碼,以匹配英語(或歐洲語言)句子中的最后一個單詞。 如果在這種情況下最后一個單詞是“ hi”,那么我要匹配“ hi”而不是“ hi”。
正則表達式(\\w+)\\.$
將匹配“ hi。”,而輸出應僅為“ hi”。 什么是正確的正則表達式?
thufir@dur:~/NetBeansProjects/regex$
thufir@dur:~/NetBeansProjects/regex$ java -jar dist/regex.jar
trying
a b cd efg hi
matches:
hi
trying
a b cd efg hi.
matches:
thufir@dur:~/NetBeansProjects/regex$
碼:
package regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String matchesLastWordFine = "a b cd efg hi";
lastWord(matchesLastWordFine);
String noMatchFound = matchesLastWordFine + ".";
lastWord(noMatchFound);
}
private static void lastWord(String sentence) {
System.out.println("\n\ntrying\n" + sentence + "\nmatches:");
Pattern pattern = Pattern.compile("(\\w+)$");
Matcher matcher = pattern.matcher(sentence);
String match = null;
while (matcher.find()) {
match = matcher.group();
System.out.println(match);
}
}
}
我的代碼是用Java編寫的,但既不在這里也不在那里。 我嚴格在尋找正則表達式,而不是Java代碼。 (是的,我知道可以用Java去除最后一個字符。)
我應該在模式中放什么正則表達式?
您可以使用先行斷言。 例如,匹配不帶句點的句子:
[\w\s]+(?=\.)
和
[\w]+(?=\.)
對於最后一個單詞(“。”之前的單詞)
如果您需要整個比賽都是硬道理,則可以使用前瞻。
\w+(?=(\.))
這與后跟一個句點的一組單詞字符匹配,而不匹配該句點。
如果您想要行中的最后一個單詞,無論行是否以句子結尾結尾,都可以使用:
\w+(?=(\.?$))
或者,如果您還想包含,!;:等,則
\w+(?=(\p{Punct}?$))
您可以使用matcher.group(1)
獲取第一個捕獲組的內容(\\w+)
在您的情況下為(\\w+)
)。 再說matcher.group(0)
, matcher.group(0)
將返回您的完整比賽。 因此,您的正則表達式幾乎是正確的。 與$
的使用有關的改進會趕上行尾。 僅當您的句子正好填滿一行時才使用此選項!
我不明白為什么會這樣,但這可行:
package regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String matchesLastWordFine = "a b cd efg hi";
lastWord(matchesLastWordFine);
String noMatchFound = matchesLastWordFine + ".";
lastWord(noMatchFound);
}
private static void lastWord(String sentence) {
System.out.println("\n\ntrying\n" + sentence + "\nmatches:");
Pattern pattern = Pattern.compile("(\\w+)"); //(\w+)\.
Matcher matcher = pattern.matcher(sentence);
String match = null;
while (matcher.find()) {
match = matcher.group();
}
System.out.println(match);
}
}
我猜正則表達式\\w+
將匹配所有單詞(doh)。 那么最后一句話就是我所追求的。 太簡單了,真的,我試圖排除標點符號,但是我想正則表達式會自動為您做到這一點。
使用此正則表達式(\\w+)\\p{Punct}
,組計數為1,這意味着您在matcher.group(0)
處得到一個帶有標點的組,而在matcher.group(1)
處matcher.group(1)
一個不matcher.group(1)
標點的matcher.group(1)
。
要使用Java編寫正則表達式,請使用: "(\\\\w+)\\\\p{Punct}"
要使用Java(以及許多其他語言)在線測試正則表達式,請參見RegexPlanet
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.