Java 将2个模式集成在一起 PrintWriter-mounceText=new PrintWriter(“C:\\Users\\markc\\OneDrive\\Documents\\NetBeansProjects\\TwitterTest\\src\\text\\mounceText.txt”); Pattern linkPattern=Pattern.compile(“https\\S*”); Pattern linkPattern2=Pattern.compile(@\\S*); 对于(int i=0;i

Java 将2个模式集成在一起 PrintWriter-mounceText=new PrintWriter(“C:\\Users\\markc\\OneDrive\\Documents\\NetBeansProjects\\TwitterTest\\src\\text\\mounceText.txt”); Pattern linkPattern=Pattern.compile(“https\\S*”); Pattern linkPattern2=Pattern.compile(@\\S*); 对于(int i=0;i,java,Java,我有一个文本文件,其中包含以“@”开头的单词和以“https”开头的单词,我使用了一种模式来删除这些单词。仅使用其中一种模式本身就可以工作,但如果我同时使用这两种模式,它们就没有任何影响 您知道如何将这两种模式整合在一起吗?您可以使用将正则表达式组合成一个组,或者 (https |@)\\S*匹配https或@字符 \\S*:匹配零个或多个非空格字符 因此,使用Pattern.compile(“(https |@)\\S*”您必须将第一次调用replaceAll(“”)返回的字符串分配给一个变量

我有一个文本文件,其中包含以“@”开头的单词和以“https”开头的单词,我使用了一种模式来删除这些单词。仅使用其中一种模式本身就可以工作,但如果我同时使用这两种模式,它们就没有任何影响

您知道如何将这两种模式整合在一起吗?

您可以使用
将正则表达式组合成一个组,或者

(https |@)\\S*
匹配
https
@
字符

\\S*
:匹配零个或多个非空格字符


因此,使用
Pattern.compile(“(https |@)\\S*”

您必须将第一次调用
replaceAll(“”
)返回的字符串分配给一个变量,然后将该字符串与第二个模式匹配,然后调用
replaceAll(“”
)。方法
replaceAll(…)
不会更改调用它的字符串实例,它会返回一个新字符串,因为Java字符串是不可变的。请尝试
Pattern.compile((https |@)\\S*)
这很有效,非常感谢!
PrintWriter sentimentText = new PrintWriter("C:\\Users\\markc\\OneDrive\\Documents\\NetBeansProjects\\TwitterTest\\src\\text\\sentimentText.txt");
        Pattern linkPattern = Pattern.compile("https\\S*");
        Pattern linkPattern2 = Pattern.compile("@\\S*");
        for (int i = 0; i < tweetsArray.size(); i++) {

            sentimentText.println(linkPattern.matcher(tweets.get(i).getText()).replaceAll(""));
            sentimentText.println(linkPattern2.matcher(tweets.get(i).getText()).replaceAll(""));

        }
        sentimentText.close();