我应该如何从我的消息中获取提到的字符串?

How should I get mentioned strings from my messge?

我不知道这是否是正确的问题,但我想从特殊字符中获取字符串。

示例:

Hi this is #myFirst post on This #StackExchange.

我要输出#myFirst#StackExchange

我试过了

(.*#[a-zA-Z_0-9])+\w+

但是,它给了我整个字符串。

您正在捕获整个字符串,因为开头有 .* 模式。

只需使用

#[a-zA-Z0-9_]+

This is a demo 显示此正则表达式将匹配的内容。

此外,请注意,此正则表达式只会让您匹配基于英文脚本的主题标签。您也可以使用 #\w+(在 Java 字符串中,#\w+)来匹配 Unicode 字符串,如 Android、\w shorthand class also matches Unicode letters.

Note that these built-in classes don't just cover the traditional ASCII range. For example, \w is equivalent to the character class [\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}].

一些sample code:

import java.util.regex.*;
...
String str = "Hi this is #myFirst post on This #StackExchange.";
String rx = "#[a-zA-Z0-9_]+";
Pattern ptrn = Pattern.compile(rx);
Matcher m = ptrn.matcher(str);
while (m.find()) {
    System.out.println(m.group(0));
}

输出:

#myFirst
#StackExchange

您可以为此使用字符串分词器。如果你的字符串每次都有#

StringTokenizer token= new StringTokenizer(YourString, "#");

   while (token.hasMoreTokens()) {
      String value = token.nextToken(); 
      System.out.println("value from token" + value);
   }

希望对您有所帮助。