Squadrons
Squadrons

Reputation: 2567

Regular expression help to skip first occurrence of a special character while allowing for later special chars but no whitespace

I'm looking for words starting with a hashtag: "#yolo"

My regex for this was very simple: /#\w+/

This worked fine until I hit words that ended with a question mark: "#yolo?".

I updated my regex to allow for words and any non whitespace character as well: /#[\w\S]*/.

The problem is I sometimes need to pull a match from a word starting with two '#' characters, up until whitespace, that may contain a special character in it or at the end of the word (which I need to capture).

Example: "##yolo?" And I would like to end up with: "#yolo?"

Note: the regular expressions are for Ruby.

P.S. I'm testing these out here: http://rubular.com/

Upvotes: 2

Views: 792

Answers (2)

arshajii
arshajii

Reputation: 129537

What about

#[^#\s]+

\w is a subset of ^\s (i.e. \S) so you don't need both. Also, I assume you don't want any more #s in the match, so we use [^#\s] which negates both whitespace and # characters.

Upvotes: 1

Orangepill
Orangepill

Reputation: 24655

Maybe this would work

#(#?[\S]+)

Upvotes: 1

Related Questions