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.
The string \"hi #how are # yo
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
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:)
Try this expression:
# *(\w+)
This says, match # then match 0 or more spaces and 1 or more letters
Here's a non-regular expression approach...
Replace all occurrences of a # followed by a space in your string with a #
myString.replaceAll("\s#", "#")
NOw split the string into tokens using the space as your delimited character
String[] words = myString.split(" ")
Finally iterate over your words and check for the leading character
word.startsWith("#")
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.
if (word.charAt(0) == '#') {
if (word.length() == 1) {
// use next word
} else {
// just use current word without the #
}
}