gpt4 book ai didi

JAVA String replaceAll hashtag内容

转载 作者:行者123 更新时间:2023-11-29 07:03:53 24 4
gpt4 key购买 nike

我使用下面的代码作为稍后使用 Twitter API 时的测试。

当我从流中获取推文并将它们存储在 mySQL 中时,如何删除主题标签以及任何尾随字符? (基本上省略了主题标签内的所有内容)

我能够使用 replaceAll 并传递“#”和“,”值并将它们替换为“”。它有效并且输出在代码下方,但是我将如何使用来替换主题标签的所有内容,包括“not”“#not”?

public class replaceAllTest {
public static void main (String args[]){
String sampleString = "This game was amazing, #not";

System.out.println("Before: " + sampleString);

sampleString = sampleString.replaceAll("#", "");
sampleString = sampleString.replaceAll(",", "");

System.out.println("After: " + sampleString);
}

}

以上代码的输出:

Before: This game was amazing, #not
After: This game was amazing not

上述代码的预期输出:

Before: This game was amazing, #not
After: This game was amazing

任何帮助将不胜感激,谢谢 Z19

最佳答案

你需要使用正则表达式

sampleString = sampleString.replaceAll("#[A-Za-z]+","");

如果您希望单独的主题标签后面没有文本,请使用 "#[A-Za-z]*"

对您的问题的评论解决了后跟不仅仅是字母字符的主题标签 - "#[^\\s]+ 其中 [^\\s]表示非空格的任何内容。

关于JAVA String replaceAll hashtag内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22056446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com