I am trying to find words starts with a specific character like:
Lorem ipsum #text Second lorem ipsum. How #are You. It's ok. Done. Something #else now.
I need to get all words starts with "#". so my expected results are #text, #are, #else
Any ideas?
The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.
As usual, the regex engine starts at the first character: 7. The first token in the regular expression is ^. Since this token is a zero-length token, the engine does not try to match it with the character, but rather with the position before the character that the regex engine has reached so far.
match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object.
Match any specific character in a setUse square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.
Search for:
So try this:
/(?<!\w)#\w+/
Or in C# it would look like this:
string s = "Lorem ipsum #text Second lorem ipsum. How #are You. It's ok. Done. Something #else now."; foreach (Match match in Regex.Matches(s, @"(?<!\w)#\w+")) { Console.WriteLine(match.Value); }
Output:
#text #are #else
Try this #(\S+)\s?
Match a word starting with # after a white space or the beginning of a line. The last word boundary in not necessary depending on your usage.
/(?:^|\s)\#(\w+)\b/
The parentheses will capture your word in a group. Now, it depends on the language how you apply this regex.
The (?:...)
is a non-capturing group.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With