简体   繁体   中英

Regex to match more possibilities (javascript)

This regex (for base64):

/[a-zA-Z0-9/+]{5}/g

Would match every 5 characters in a string. So if I have:

"19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAw"

the matches are:

  1. 19jZ2
  2. uLj5O
  3. Xm5+j
  4. p6vLz
  5. 9PX29
  6. /j5+v
  7. /aAAw

How would I write a regex that would result in the following matches?

  1. 19jZ2
  2. 9jZ2u
  3. jZ2uL
  4. Z2uLj
  5. 2uLj5
  6. uLj5O
  7. and so on...

(^Literally every possible 5 consecutive characters in the string)

How about this:

"19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAw".split('').map(function(elm, i, arr) { 
    return arr.slice(i,i+5).join('') }
).slice(0,-4)

Based on adeneo's comment :

var result = [],
    s = '19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAw';
while (s.length > 4) {
    result.push(s.substr(0, 5));
    s = s.substr(1);
}

Here is a suggestion :

function split(s) {
    var allowed = /^[a-z\d/+]{5}/i,
        result = [],
        match;
    while (s.length > 4) {
        match = s.match(allowed);
        match && result.push(match[0]);
        s = s.substr(1); // removes first char
    }
    return result;
}

The regex looks for the first five chars for each loop :

split('19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAw'); // ['19jZ2', '9jZ2u', ...]
split('19jZ2=uLj5OXm5+jp6vLz9PX29/j5+v/aAAw'); // ['19jZ2', 'uLj5O', ...]

A simple ([a-zA-Z0-9+\\/]{5}) could do it for this specific input

Live DEMO

Or (?:"|\\G(?<!^))([a-zA-Z0-9+\\/]{5}|[a-zA-Z0-9+\\/]+)(?=.*?") if your string is between quotes

Live DEMO

Or (?:"|\\G(?<!^))([a-zA-Z0-9+\\/]{5})(?=(?:[a-zA-Z0-9+\\/]{5})*") if your string count is exactly a multiple of 5

Live DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM