0

I have the following regex:

/#([A-Za-z0-9_]+)/g

http://regexr.com/393bh

How can I make it so that there must be a space before the hashtag for the regex to be valid (i.e. the second line in the link above shouldn't match).

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631

3 Answers3

2

From:

/#([A-Za-z0-9_]+)/

To:

/\s#([A-Za-z0-9_]+)/

More information on matching space/s: Matching a space in regex

http://jsfiddle.net/PeV57/

Community
  • 1
  • 1
Alex
  • 34,899
  • 5
  • 77
  • 90
  • Okay, how do I make it not include the space though? –  Jul 02 '14 at 02:44
  • 1
    @user3769178: Well the hash-tag part is between brackets, you can use regex capturing techniques for this. Every programming language has some kind of api for this (but you didn't specify your environment). – Willem Van Onsem Jul 02 '14 at 02:46
1

You can simply add a space in your regex as follows:

/ #([A-Za-z0-9_]+)/g

To not include the space in the match, you can do:

/(?:\s)(#[A-Za-z0-9_]+)/g
sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • How would I make it not include the space in the match? –  Jul 02 '14 at 02:45
  • @user3769178, Answer updated (second regex). Now if you use that regex, the ___first captured group___ will not contain the space. – sshashank124 Jul 02 '14 at 02:50
1

Use \K or look behind to not to include space at the end result.

/ \K#([A-Za-z0-9_]+)/g

OR

(?<=\s)#([A-Za-z0-9_]+)

DEMO

First captured group contains the string test. If you want the captured group to contain #, the use this regex (?<=\s)(#[A-Za-z0-9_]+)

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274