How to retrieve hashtags from string using this PHP regex in Java?

Viewed 73

I am a PHP developer and it has been only a few months since I started learning Java. Here, I have a function in PHP to retrieve the hashtags from a string.

{
    preg_match_all('/(^|[^a-z0-9_])#([a-z0-9_]+)/i', $text, $matchedHashtags);
    $hashtag = '';
    if (!empty($matchedHashtags[0])) {
        foreach ($matchedHashtags[0] as $match) {
            $hashtag .= preg_replace("/[^a-z0-9]+/i", "", $match) . ',';
        }
    }
    return rtrim($hashtag, ',');
}

This function returns a new strings containing the hashtags, separated by a comma. My question is, how to achieve this exact function in java? Regards.

1 Answers

One option might be to use a single pattern, instead of first matching and then replacing.

Then you can either concatenate the results in a string, or add the results to a list and use String.join with a comma.

\B#\w*[A-Za-z]\w*
  • \B Match at a position where \b does not match
  • #\w*[A-Za-z]\w* Match # and at least a single char A-Za-z (if you don't want to match only digits or underscores according to the comments)

Java demo | Regex demo

For example

List<String> matches = new ArrayList<String>();
Matcher m = Pattern.compile("\\B#\\w*[A-Za-z]\\w*")
    .matcher("#test @#$#test a#test,#2021, #__");
while (m.find()) {
    matches.add(m.group());
}

System.out.println(String.join(",", matches));

Output

#test1,#test2
Related