[ACCEPTED]-Find the words start from a special character java-regex
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
Try this expression:
# *(\w+)
This says, match # then 1 match 0 or more spaces and 1 or more letters
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 #
}
}
Here's a non-regular expression approach...
Replace 6 all occurrences of a # followed by a space 5 in your string with a #
myString.replaceAll("\s#", "#")
NOw 4 split the string into tokens using the space 3 as your delimited character
String[] words 2 = myString.split(" ")
Finally iterate over 1 your words and check for the leading character
word.startsWith("#")
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.