vfclists
vfclists

Reputation: 20251

How to match regular expressions only if they are surrounded with proper punctuation characters in Javascript?

I want to much Redmine issue numbers in Version Control commit messages, which are numbers preceded by a # sign, eg #123, #456 etc, but I only want to match them if they are surrounded by a punctuation character set, or are the beginning or end of the line. eg '#234aa, #567' should match only #567. ', - ;#456,,' should match #456 because ',-; ' are all in the punctuation character set. I have tried an example expression

function myFunction()
{
    var str="erwet,#3456 #623 #345 fdsfsd"; 
    var n=str.match(/\#[\d+]+[\s]/g);
    document.getElementById("demo").innerHTML=n;
}

I also want to match them into an array or a list, but the demo I am trying matches them into a single string.

Upvotes: 0

Views: 334

Answers (1)

kieran
kieran

Reputation: 1537

Okay, so I think I have a regex that does the job, the fact that it's matching punctuation made a couple of sentences in your example a little confusing but here goes:

var re = /(?:^|['".,;:\s])(#\d+)(?:['".,;:\s]|$)/;​

Which can be broken down as:

(?:^|['".,;\s]) //matches either the beginning of the line, or punctuation
(#\d+ )         //matches the issue number
(?:['".,;:\s]|$)//matches either punctuation, whitespace, or the end of the line

So we get:

re.test('#234aa, #567') //true
re.exec('#234aa, #567') //["#567", "#567", "", index: 8, input: "#234aa, #567"] 
re.test("', - ;#456,,'")//true
re.exec("', - ;#456,,'")//[";#456,", "#456", index: 5, input: "', - ;#456,,'"]   

I'm not so sure about the \s in the last bit, because that's neither punctuation nor end of line, but you had it in your base code so I assume it's something you want.

Upvotes: 1

Related Questions