Extract Hashtags from Text
This program extracts hashtags from text using regex.
Problem Statement
Write a Java program to extract hashtags from "Learning #Java at #Eduinq".
Source Code
| 1 | import java.util.regex.*; |
| 2 | public class RegexExtractHashtags { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq Regex Extract Hashtags"); |
| 5 | String str="Learning #Java at #Eduinq"; |
| 6 | Pattern p=Pattern.compile("#\\w+"); |
| 7 | Matcher m=p.matcher(str); |
| 8 | while(m.find()) System.out.println("Extracted hashtag: "+m.group()); |
| 9 | } |
| 10 | } |
Program Output
Eduinq Regex Extract Hashtags Extracted hashtag: #Java Extracted hashtag: #Eduinq
Explanation
The regex #\w+ matches a hash symbol followed by one or more word characters, and the Matcher's find() method loops through the text extracting each hashtag it encounters.