user3213851
user3213851

Reputation: 1108

Java regular expression not working as expected

I am using java regular expression to split my string into substrings of 2 characters each. I am using the following code.

import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class HelloWorld{

    public static void main(String []args)
    {
        String str = "admins";
        String delimiters = "([a-z]{2})";

        String[] tokensVal = str.split(delimiters);

        System.out.println("Count of tokens = " + tokensVal.length);
        System.out.println(Arrays.toString(tokensVal));
    }
}

But running the following code prints the value of count to zero and prints an empty array.

Upvotes: 2

Views: 159

Answers (3)

Jyoti Ranjan Pattnaik
Jyoti Ranjan Pattnaik

Reputation: 713

if you are interested, Here is a solution without using Regex:

String str = "admins";
    String splittedStr = null;
    for (int i = 0; i < str.length()-1;) {
        splittedStr = new String (new char[] {str.charAt(i),str.charAt(i+1)});
        i=i+2;
        System.out.println(splittedStr);
    }

output:
ad
mi
ns

Upvotes: 0

user1134181
user1134181

Reputation:

import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class ApachePOI{
     public static void main(String []args) {
         String str = "admins";
         String delimiters = "(?<=\\G.{2})";

         String[] tokensVal = str.split(delimiters);


         System.out.println("Count of tokens = " + tokensVal.length);
         System.out.println(Arrays.toString(tokensVal));
     }
}

output:

Count of tokens = 3
[ad, mi, ns]

Upvotes: 8

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Using the regex as delimiter will try to split the string by eliminating the characters matched in by the expression. I guess you want these characters itself as a substring so String.split() will not help.

Try this:

    String str = "admins";
    Pattern pattern = Pattern.compile(".{2}");
    Matcher matcher = pattern.matcher(str);
    while (matcher.find()) {
        String match = matcher.group();
        System.out.println(match);
    }

Output:

ad
mi
ns

Upvotes: 3

Related Questions