2011-02-25 51 views
7

我想查找以“#”符号开头的单词,该单词在java中是一个字符串。标志和单词之间也可以有空格。查找单词从特殊字符开始java

"hi #how are # you"须发出输出:

how 
you 

我已经和正则表达式试过,但还是没能找到一个合适的模式。请帮助我。

谢谢。

回答

10

使用#\s*(\w+)作为您的正则表达式。

String yourString = "hi #how are # you"; 
Matcher matcher = Pattern.compile("#\\s*(\\w+)").matcher(yourString); 
while (matcher.find()) { 
    System.out.println(matcher.group(1)); 
} 

这将打印出:

how 
you 
+0

感谢您的帮助ide,乔和knutson。有用。我也想获得所有在最后一个#符号后出现的单词。 '例如:“嗨#how是#你在做什么”应该给出输出结果作为你如何去做“是否有实现这一点? – gishara 2011-02-25 06:34:10

+0

这是一个不同的问题,虽然你可以用正则表达式来解决它(''Pattern.compile(“#\\ s *([^#] + $ | \\ w +)”)'),但它可能会让人困惑...... – ide 2011-02-25 06:39:43

+0

非常感谢您的帮助。那是我想要的。 :) – gishara 2011-02-25 06:43:56

0

试试这个表达式:

# *(\w+) 

此说,比赛#然后匹配0或多个空格和1个或多个字母

+0

为什么在字符类的空间? – NullUserException 2011-02-25 06:24:20

+0

我在想我自己,thx – Joe 2011-02-25 06:25:36

0

我想你可能是最好关闭使用拆分方法上的字符串( mystring.split(''))并分别处理这两个案例。如果你要让多人更新代码,正则表达式可能很难维护和阅读。

if (word.charAt(0) == '#') { 
    if (word.length() == 1) { 
    // use next word 
    } else { 
    // just use current word without the # 
    } 
} 
0

这里有一个非正则表达式的方法...

  1. 替换#,然后在你的字符串与空间的所有出现a#

    myString.replaceAll(“\ s#”,“#”)

  2. 现在使用空间作为分隔字符

    字符串[]字=​​ myString.split(”“)

  3. 最后迭代你的话,检查前导字符的字符串分割成令牌

    word.startsWith( “#”)

-1
 String mSentence = "The quick brown fox jumped over the lazy dog."; 

     int juIndex = mSentence.indexOf("ju"); 
     System.out.println("position of jumped= "+juIndex); 
     System.out.println(mSentence.substring(juIndex, juIndex+15)); 

     output : jumped over the 
     its working code...enjoy:)