简体   繁体   English

找到从特殊字符java开始的单词

[英]Find the words start from a special character java

I want to find the words that start with a "#" sign in a string in java. 我想在java中的字符串中找到以“#”符号开头的单词。 There can be spaces between the sign and the word as well. 标志和单词之间也可以有空格。

The string "hi #how are # you" shall give the output as : 字符串"hi #how are # you"将输出为:

how
you

I have tried this with regex, but still could not find a suitable pattern. 我用regex尝试了这个,但仍然找不到合适的模式。 Please help me on this. 请帮帮我。

Thanks. 谢谢。

Use #\\s*(\\w+) as your regex. 使用#\\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));
}

This will print out: 这将打印出来:

how
you

Try this expression: 试试这个表达式:

# *(\w+)

This says, match # then match 0 or more spaces and 1 or more letters 这样说,匹配#然后匹配0或更多空格和1个或多个字母

I think you may be best off using the split method on your string (mystring.split(' ')) and treating the two cases separately. 我认为你可能最好在字符串上使用split方法(mystring.split(''))并分别处理这两种情况。 Regex can be hard to maintain and read if you're going to have multiple people updating the code. 如果您要让多个人更新代码,正则表达式很难维护和阅读。

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

Here's a non-regular expression approach... 这是一种非正则表达方式......

  1. Replace all occurrences of a # followed by a space in your string with a # 用#替换字符串中所有出现的#后跟一个空格

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

  2. NOw split the string into tokens using the space as your delimited character 否则使用空格作为分隔字符将字符串拆分为标记

    String[] words = myString.split(" ") String [] words = myString.split(“”)

  3. Finally iterate over your words and check for the leading character 最后迭代你的单词并检查主角

    word.startsWith("#") word.startsWith( “#”)

     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:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM