I’m looking for a regular expression in Javascript that would match, in a string like
@Mr. Smith Hello !
, where Mr. Smith is the name of the user, the occurrences
Mr. Mr. Smith Mr. Smith Hello Mr. Smith Hello !
For now, every regular expression that I tried returned
@Mr. Smith Hello ! and Mr. Smith Hello !,
while neglecting Mr., Mr. Smith and Mr. Smith Hello…
i have tried this:
/^@(.*) /, /^@(.*)* / and /^@([^ ].*) /
Thanks for your help !
A single regular expression cannot return overlapping text as separate matches, because each match consumes part of the input text. However, you can create nested capture groups, like this (Demo: http://www.rubular.com/r/bsu52a1eL9):
Of course this will only work for the exact string format you gave, having exactly 3 spaces / 4 separate words. A better solution is to make use of the
substringandsplitmethods, then you can recombine the parts manually:Demo: http://jsfiddle.net/jbk4h/