Reputation: 2598
If we have a
string s = 'abcdxefyghijxlm'
I can split it by 2 characters using
s.match(/.{1,2}/g)
and I will get
['ab', 'cd', 'xe', 'fy', 'gh', 'ij', 'xl', 'm']
How would I split it this way while at the same time isolating specific characters 'x'
and 'y'
?
For the example above, I would like to get the following result
['ab', 'cd', 'x', 'ef', 'y', 'gh', 'ij', 'x', 'lm']
EDIT
I forgot to mention that I am only targetting alphabetical characters to be split into pairs except x
and y
. So currently, the regex I have above does not actually work for when I have something like s = '{"abcd":"12"}'
as it will result to
['{"', 'ab', 'cd', '":', '"1, '2"', '}']
instead of
[ '{', '"', 'ab', 'cd', '"', ':', '"', '1', '2', '"', '}']
Upvotes: 0
Views: 81
Reputation: 422
/((?![x|y|\W|\d|"])..|.)/gi
(?!)
Negative Lookahead => Assert that the Regex [x|y]
does not match
[x|y]
Match a single character => x or y (case insensitive)
[\W]
matches any non-word character
\d
matches a digit
g
modifier: global. All matches (don't return after first match)
i
modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z]
)
const str = `abcdxefyghijxlm{"abcd":"12"}`;
let m = str.match(/((?![x|y|\W|\d|"])..|.)/gi);
console.log(m);
Upvotes: 0
Reputation: 1074208
Use an alternation (this|that
): /[a-wz]{2}|./g
That looks for:
[a-wy]
- any two characters of the English alphabet except x
and y
, or.
- any single characterAlternations choose the first that matches, so this will prefer [a-wz]{2}
over .
where both match.
Example:
Live Example:
let s = "abcdxefyghijxlm{\"abcd\":\"12\"}";
console.log(s.match(/[a-wz]{2}|./g));
.as-console-wrapper {
max-height: 100% !important;
}
Note: The above is case sensitive. If you don't want that, add the i
flag: /[a-wz]{2}|./gi
Upvotes: 3