Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find words that start with a specific character

Tags:

c#

regex

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?

like image 987
Vijay Narayan Avatar asked Apr 20 '10 21:04

Vijay Narayan


People also ask

How do you search for a regex pattern at the beginning of a string?

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.

Which character starts with in regex?

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.

How do you search for a regex pattern at the beginning of a string python?

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.

How do I match a specific character in regex?

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.


3 Answers

Search for:

  • something that is not a word character then
  • #
  • some word characters

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 
like image 181
Mark Byers Avatar answered Oct 13 '22 09:10

Mark Byers


Try this #(\S+)\s?

like image 20
Peter Avatar answered Oct 13 '22 08:10

Peter


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.

like image 20
Jeff B Avatar answered Oct 13 '22 10:10

Jeff B