0

Using regular expression howto obtain all combination of 2 characters on a string?

Example: "abcdefghi", Result: ab,bc,cd,de,ef Using 3 chars: abc,bcd,cde,def...

I try with: /.{2}/g but is not recursive, only match ab,cd,ef but not bc,de, etc.

Howto make this?

e-info128
  • 3,727
  • 10
  • 40
  • 57
  • I don't think I've ever seen a regex implementation that supported overlapping matches. If you want to find out if the particular implementation you're using does - you'll need to give us some slight hint as to which implementation that is. – jasonharper Dec 20 '16 at 03:27
  • Is php, i have a big number, need separate in order (left to right) all combinations of 2 digits to lentght/2 of value to find. – e-info128 Dec 20 '16 at 03:30
  • 1
    Possibly relevant: http://stackoverflow.com/questions/18501538/finding-all-3-character-length-substrings-in-a-string ... one of the answers suggests that you _can't_ use regex here, because once a letter is consumed, it isn't available anymore. – Tim Biegeleisen Dec 20 '16 at 03:30
  • 1
    Possible duplicate of [How can I match overlapping strings with regex?](http://stackoverflow.com/questions/20833295/how-can-i-match-overlapping-strings-with-regex) – Sebastian Simon Dec 20 '16 at 03:30
  • 3
    So why do you think a regex is the answer? This sounds like a simple case of string slicing. – jasonharper Dec 20 '16 at 03:31

1 Answers1

1

You can try this:

(?=(\w{2}))\w

Sample regex example here.

Java Sample Code:

public static void printVal(String str,int length)
{
    final String regex="(?=(\\w{"+length+"}))\\w";
    final Pattern pattern=Pattern.compile(regex,Pattern.MULTILINE);
    final Matcher matcher=pattern.matcher(str);
    System.out.println("length :"+length);        
    while(matcher.find())
    {
        System.out.println(matcher.group(1));
    }

}

Sample Input:

printVal("abcdefghi",2);
printVal("abcdefghi",3);
printVal("abcdefghi",4);

Sample Output:

length :2
ab
bc
cd
de
ef
fg
gh
hi
length :3
abc
bcd
cde
def
efg
fgh
ghi
length :4
abcd
bcde
cdef
defg
efgh
fghi
Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43