[ACCEPTED]-Find the words start from a special character java-regex

Accepted answer
Score: 13

Use #\s*(\w+) as your regex.

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

0

Score: 0

Try this expression:

# *(\w+)

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

Score: 0

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

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

Here's a non-regular expression approach...

  1. Replace 6 all occurrences of a # followed by a space 5 in your string with a #

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

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

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

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

    word.startsWith("#")

More Related questions