HP.
HP.

Reputation: 19896

Javascript regex for hashtag with number only

I want to match these kind of hashtag pattern #1, #4321, #1000 and not:

But special character like comma, period, colon after the number is fine, such as #1.. Think of it as hashtag at the end of the sentence or phrase. Basically treat these as whitespace.

Basically just # and a number.

My code below doesn't meet requirement because it takes leading zero and it has an ugly space at the end. Although I can always trim the result but doesn't feel it's the right way to do it

reg = new RegExp(/#[0-9]+ /g);   
var result;
while((result = reg.exec("hyha #12  gfdg #01 aa #2e #1. #101")) !== null) {
    alert("\"" + result + "\"");
}

http://jsfiddle.net/qhoc/d3TpJ/

That string there should just match #12, #1 and #101

Please help to suggest better RegEx string than I had. Thanks.

Upvotes: 0

Views: 1249

Answers (2)

bgusach
bgusach

Reputation: 15153

This should work

reg = /(#[1-9]\d*)(?: |\z)/g;   

Notice the capturing group (...) for the hash and number, and the non capturing (?: ..) to match the number only if it is followed by a white space or end of string. Use this if you dont want to catch strings like #1 in #1.. Otherwise the other answer is better.

Then you have to get the captured group from the match iterating over something like this:

myString = 'hyha #12  gfdg #01 aa #2e #1. #101';
match = reg.exec(myString);
alert(match[1]);

EDIT

Whenever you are working with regexps, you should use some kind of tool. For desktop for instance you can use The regex coach and online you can try this regex101

For instance: http://regex101.com/r/zY0bQ8

Upvotes: 1

Qtax
Qtax

Reputation: 33908

You could use a regex like:

#[1-9]\d*\b

Code example:

var re = /#[1-9]\d*\b/g;
var str = "#1 hyha #12 #0123 #5 gfdg #2e ";
var matches = str.match(re); // = ["#1", "#12", "#5"]

Upvotes: 2

Related Questions