查找以特殊字符开头的单词 java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5114200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:31:10  来源:igfitidea点击:

Find the words start from a special character java

javaregex

提问by gishara

I want to find the words that start with a "#" sign in a string in java. There can be spaces between the sign and the word as well.

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

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. Please help me on this.

我已经用正则表达式尝试过这个,但仍然找不到合适的模式。请帮我解决这个问题。

Thanks.

谢谢。

回答by ide

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

回答by Joe

Try this expression:

试试这个表达:

# *(\w+)

This says, match # then match 0 or more spaces and 1 or more letters

这表示,匹配 # 然后匹配 0 个或多个空格和 1 个或多个字母

回答by knutson

I think you may be best off using the split method on your string (mystring.split(' ')) and treating the two cases separately. Regex can be hard to maintain and read if you're going to have multiple people updating the code.

我认为您最好在字符串上使用 split 方法 (mystring.split(' ')) 并分别处理这两种情况。如果您要让多人更新代码,则 Regex 可能难以维护和阅读。

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

回答by mmccomb

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#", "#")

  2. NOw split the string into tokens using the space as your delimited character

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

  3. Finally iterate over your words and check for the leading character

    word.startsWith("#")

  1. 将字符串中所有出现的 # 后跟空格替换为 #

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

  2. 现在使用空格作为分隔字符将字符串拆分为标记

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

  3. 最后迭代你的话并检查主角

    word.startsWith("#")

回答by siddhartha shankar

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