i have string:
const text = 'A Jack# Jack#aNyWord Jack, Jack';
i want search word "Jack" only, but if Jack contain # character, its say true mean match.
i try like:
const text = 'A Jack# Jack#aNyWord Jack, Jack';
const regexpWords = /Jack(?=,|#)/g;
console.log(text.match(regexpWords));
result say: Array ["Jack", "Jack", "Jack"]
My expected output is: Array ["Jack#", "Jack#aNyWord", "Jack", "Jack"]
except word "Jack,"
how can i do with this
2
Answers
If you want the
#
in the match, then you don’t want a lookahead ((?=___)
) because lookahead and lookbehind aren’t included in matches. You haven’t said what should be valid following the#
, but if I assume any letter or number, then:That says
Jack
#
followed by any number of[a-zA-Z0-9]
. I do that by wrapping#[a-zA-Z0-9]*
in a non-capturing group ((?:___)
) and then making the group optional with?
I’ve used
[a-zA-Z0-9]*
for the letters following the#
because the expression doesn’t have thei
flag (case-insensitive matching, would matchjack
). You could use[a-z0-9]*
if you’re going to add thei
flag. (You might also usew
, but it allows_
which you may or may not want.)MDN’s regular expressions documentation is quite good: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
If you want the words with Jack and there must be at least
Jack#
you can match the part of the string containing Jack# using a negated character class[^,n]*
excluding matching comma’s or newlines.If there is a match, then split the match on one or more whitspace characters and filter the result containing the word Jack using word boundaries
b
After the question was edited, you can match all words with Jack:
bJack[^,s]*
or(?<!S)Jack[^,s]*
See a regex demo for the matches.