0

我想在java中的字符串中找到唯一以“#”符号开头的第一个单词。符号和单词之间也不能有空格。

字符串“hi #how are # you”将输出为:

如何

我已经用正则表达式尝试了这个,但仍然找不到合适的模式。请帮助我。

谢谢。

4

4 回答 4

1
String str ="hi #how are # you";
if (str.contains("#")) {
        int pos = str.indexOf("#");

        while (str.charAt(pos + 1) == ' ')
            pos++;


        int last = str.indexOf(" ", pos + 1);

        str = str.substring(pos + 1, last);
        System.out.println(str);
    }
else{

}

输出: 如何

于 2012-06-07T17:19:49.603 回答
1

尝试这个

replaceFirst("^.*?(#\\S+).*$", "$1");

不完全漂亮,但应该工作。

这假设字符串具有这样的标记。如果不是,那么您可能需要在提取令牌之前检查它是否与正则表达式匹配:

matches("^.*?(#\\S+).*$");

请注意,此方法将匹配"#sdfhj"."sdfkhk#sdfhj sdf"

如果要排除这种情况,可以将正则表达式修改为"^.*?(?<= |^)(#\\S+).*$".

于 2012-06-07T17:22:03.287 回答
1

我认为 xx#xx 是错误的词。我是真的试试这个(如果不是"#(\\w+)"在 Pattern 中使用,m.group(1)而是m.group(2)

String str ="ab cd#ef #gh";
Pattern pattern=Pattern.compile("(^|\\s)#(\\w+)");
Matcher m=pattern.matcher(str);
if(m.find())
    System.out.println(m.group(2));
else
    System.out.println("no match found");

"ab cd#ef #gh"结果- >gh

"#ab cd#ef #gh"结果- >ab

于 2012-06-07T17:37:46.767 回答
0

你可以试试这个正则表达式:

"[^a-zA-Z][\\S]+?[\\s]"

除非您知道在这种情况下要从哪个特定字符开始

"#[\\S]+?[\\s]"
于 2012-06-07T17:19:01.663 回答