gpt4 book ai didi

使用自定义正则表达式替换 Java 字符串

转载 作者:行者123 更新时间:2023-12-01 20:04:46 24 4
gpt4 key购买 nike

我有一个可以传输 Twitter 数据的 Java 应用程序。

假设我有一个 String text = tweet.getText() 变量。

在一篇文本中,我们可以有一个或多个@MentionedUser。我不仅想删除 @,还想删除用户名。如何使用 replaceAll 执行此操作而不触及字符串的其余部分?

谢谢。

最佳答案

我想使用 (^|\s)@\w+($|\s) 因为您可以在输入中获取电子邮件,例如:

a @twitter username and a simple@email.com another @twitterUserName

所以你可以使用:

String text = "a @twitter username and a simple@email.com another @twitterUserName";
text = text.replaceAll("(^|\\s)@\\w+($|\\s)", "$1$2");
// Output : a username and a simple@email.com another

详细信息:

  1. (^|\s)哪个匹配 ^字符串开头或 |一个空格\s
  2. @\w+匹配 @ 后跟一个或多个单词字符,相当于 [A-Za-z0-9_]
  3. ($|\s)哪个匹配 $字符串结尾或 |一个空格\s
<小时/>

如果您想更深入地指定 Twitter 用户名的正确语法,我会阅读此文 article here他们提到了一些有用的信息:

  • Your username cannot be longer than 15 characters. Your name can be longer (50 characters), but usernames are kept shorter for the sake of ease.

  • A username can only contain alphanumeric characters (letters A-Z, numbers 0-9) with the exception of underscores, as noted above. ...

根据此规则,您也使用此正则表达式:

(?i)(^|\s)@[a-z0-9_]{1,15}($|\s)

关于使用自定义正则表达式替换 Java 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47597369/

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