Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java PatternSyntaxException:不匹配的结束';(';_Java - Fatal编程技术网

Java PatternSyntaxException:不匹配的结束';(';

Java PatternSyntaxException:不匹配的结束';(';,java,Java,我需要删除Twitter消息中的所有URL。我有一个包含大约200000条此类消息的文件,因此速度至关重要!为此,我使用Java作为编程语言,下面是我的代码示例: public String performStrip(){ String tweet = this.getRawTweet(); String urlPattern = "((https?|http)://(bit\\.ly|t\\.co|lnkd\\.in|tcrn\\.ch)\\S*)\\b"; Pat

我需要删除Twitter消息中的所有URL。我有一个包含大约200000条此类消息的文件,因此速度至关重要!为此,我使用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 21

位于java.util.regex.Pattern.error(Pattern.java:1924)
位于java.util.regex.Pattern.compile(Pattern.java:1669)
Pattern.(Pattern.java:1337)
位于java.util.regex.Pattern.compile(Pattern.java:1022)
位于java.lang.String.replaceAll(String.java:2210)
位于com.anturo.preprocess.url.UrlStripper.performStrip(UrlStripper.java:47)
在com.anturo.preprocess.testing.ReadIn.(ReadIn.java:35)
位于com.anturo.preprocess.testing.Main.Main(Main.java:6)

关于这个错误,我已经研究了多个类似的问题,但是到目前为止没有一个是有效的…希望有人能在这里帮助我。

问题是URL中可能有regex特殊字符,如您所见

简短的解决方案:使用。您的代码将是:

tweet = tweet.replaceAll(Pattern.quote(m.group(i)),"").trim();
注意:仅在JDK1.5之后可用,但您确实使用了这个或更好的版本,对吗

另一种解决方案是简单地使用
.replace()

与它的名字所暗示的
.replaceAll()
不同,
.replace()
会替换所有出现的内容;只是它不将正则表达式作为替换字符串。另请参见
.replaceFirst()

最后但并非最不重要的一点是,您似乎误用了
.group()
!您的循环应该是:

while (m.find())
    tweet = tweet.replace(m.group(), "").trim();

这里不需要
i
变量;
m.group(i)
将通过在正则表达式中捕获group
i
来返回匹配的内容。

Uhm,为什么不使用
URI
类来识别URL?这将比使用正则表达式更快…您可以发布完整的堆栈跟踪吗?更重要的是:
(http:http)<代码>可以用<代码> http://c>替换。我不知道你为什么这样做,但是这是一个潜在危险的ID,有人依赖它。它不会发现除了HTTP或HTTPS之外的URI,而且有很多(1)-这可能被用作攻击向量。(1)@Bex,我同意,但这只是为了删除推特消息中所有不需要的元素,以便在我的自然语言处理等工作中使用。无论如何,谢谢你的评论!
tweet = tweet.replace(m.group(i), "").trim();
while (m.find())
    tweet = tweet.replace(m.group(), "").trim();