简体   繁体   English

Java正则表达式无法按预期工作

[英]Java regular expression not working as expected

I am using java regular expression to split my string into substrings of 2 characters each. 我使用java正则表达式将我的字符串拆分为每个2个字符的子字符串。 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. 但是运行以下代码会将count的值打印为零并打印一个空数组。

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]

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. 我想你想把这些字符本身作为子字符串,所以String.split()无济于事。

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

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 MI
ns NS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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