我需要删除在Twitter消息中找到的所有URL。我有一个文件,大约有20万这样的信息,所以速度是至关重要的!为此,我使用Java作为编程语言,下面是我的代码示例:
public String performStrip(){
String tweet = this.getRawTweet();
String urlPattern = "((https?|http)://(bit\\.ly|t\\.co|lnkd\\.in|tcrn\\.ch)\\S*)\\b";
Pattern p = Pattern.compile(urlPattern,Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(tweet);
int i = 0;
while (m.find()) {
tweet = tweet.replaceAll(m.group(i),"").trim();
i++;
}
return tweet;
}在下列情况下,这是很好的:
http://t.co/nhWp9hldEH -> (empty string)
http://t.co/nhWp9hldEH" -> "
http://t.co/nhWp9hldEH)aaa" -> aaa"
aaa(http://t.co/nhWp9hldEH" -> aaa("
aaa(http://t.co/nhWp9hldEH)" -> aaa()"然而,当我谈到一个案件时,如下所示:
http://t.co/nhWp9hldEH)aaa"我犯了个错误
java.util.regex.PatternSyntaxException: Unmatched closing ')' near index 21http://t.co/nhWp9hldEH)aa
at java.util.regex.Pattern.error(Pattern.java:1924)
at java.util.regex.Pattern.compile(Pattern.java:1669)
at java.util.regex.Pattern.<init>(Pattern.java:1337)
at java.util.regex.Pattern.compile(Pattern.java:1022)
at java.lang.String.replaceAll(String.java:2210)
at com.anturo.preprocess.url.UrlStripper.performStrip(UrlStripper.java:47)
at com.anturo.preprocess.testing.ReadIn.<init>(ReadIn.java:35)
at com.anturo.preprocess.testing.Main.main(Main.java:6)我已经研究过关于这个错误的多个类似的问题,但是到目前为止没有一个问题有效.希望有人能帮我。
发布于 2014-02-17 09:09:19
问题是,您可能在URL中有regex特殊字符,如您所见。
简短的解决方案:使用Pattern.quote()。然后,您的代码将是:
tweet = tweet.replaceAll(Pattern.quote(m.group(i)),"").trim();注意:只在JDK 1.5之后才可用,但是您确实使用了这个或更好,对吗?
另一个解决方案是简单地使用.replace()
tweet = tweet.replace(m.group(i), "").trim();与其名称对.replaceAll()的含义不同,.replace()确实替换了所有的事件;它只是不以正则表达式作为替换字符串。另见.replaceFirst()。
最后但并非最不重要的是,您似乎在滥用.group()!您的循环应该是:
while (m.find())
tweet = tweet.replace(m.group(), "").trim();这里不需要i变量;对于一个匹配项,m.group(i)将返回正则表达式中捕获组i所匹配的内容。
https://stackoverflow.com/questions/21824674
复制相似问题