jackSparrow jackSparrow - 1 month ago 5
Java Question

I want to find all words using java regex, that starts with "#" and ends with space or "."

This is a sample string

hi #myname, you got #amount


I want to find all words using java regx,
that starts with
#
and ends with space or
.

example
#myname
,
#amount


I tried the following Regex, but it doesn't work.

String regx = "^#(\\s+)";

Answer

This one should be the way:

#(\w+)(?:[, .]|$)
  • # matches # literally
  • \w is a word with at least one letter
  • (?:) is non-capturing group
  • [, .]|$ is set of ending characters including the end of line $

For more information check out Regex101.

In Java don't forget to escape with double \\:

String str = "hi #myname, you  got #amount";
Matcher m = Pattern.compile("#(\\w+)(?:[, .]|$)").matcher(str);
while (m.find()) {
   ...
}
Comments