Java 正则表达式调整

标签 java regex

任何人都可以帮助我哪里做错了吗?

我的示例文本:

{[|Name:A|Class:1|Sex:Male|][|Name:B|Class:2|Sex:Female|][|Name:C|Class:3|Sex:Male|]}

预期输出:

|Name:A|Class:1|Sex:Male|
Name:A
Class:1
Sex:Male
|Name:B|Class:2|Sex:Female|
Name:B
Class:2
Sex:Female
|Name:C|Class:3|Sex:Male|
Name:C
Class:3
Sex:Male

当前输出:

|Name:A|Class:1|Sex:Male|
Name:A
Sex:Male
|Name:B|Class:2|Sex:Female|
Name:B
Sex:Female
|Name:C|Class:3|Sex:Male|
Name:C
Sex:Male

我的程序:

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

public class Regex {

    public static void main(String[] args) {

        String example = "{[|Name:A|Class:1|Sex:Male|][|Name:B|Class:2|Sex:Female|][|Name:C|Class:3|Sex:Male|]}";

        Pattern curlyBraces = Pattern.compile("\\[(.*?)\\]");

        Matcher m = curlyBraces.matcher(example);
        while (m.find()) {
            System.out.println(m.group(1));
            String element = m.group(1);
            Pattern pipe = Pattern.compile("\\|(.*?)\\|");
            Matcher mPipe = pipe.matcher(element);
            while (mPipe.find()) {
                System.out.println(mPipe.group(1));
            }
        }
    }
}

最佳答案

你的问题是 "\\|(.*?)\\|" 只会匹配 |Name:A||Sex:Male | 在行中

|Name:A|Class:1|Sex:Male|

因为正则表达式消耗了它匹配的字符,所以 Name:AClass:1 之间的 | 因此只能匹配一次.

使用lookaround assertions解决这个问题 - 他们不会使用他们匹配的文本:

        Pattern pipe = Pattern.compile("(?<=\\|).*?(?=\\|)");
        Matcher mPipe = pipe.matcher(element);
        while (mPipe.find()) {
            System.out.println(mPipe.group(0));
        }

如果您不期望空值,另一种可能性是匹配所有“非管道”字符:

        Pattern pipe = Pattern.compile("[^|]+");
        Matcher mPipe = pipe.matcher(element);
        while (mPipe.find()) {
            System.out.println(mPipe.group(0));
        }

关于Java 正则表达式调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35194704/

相关文章:

regex - 正则表达式 - 搜索直到出现特定字符串

c# - 使用 Regex.Replace 替换字符串中的前 16 位数字

java - 通过 bash 脚本自动检测 tomcat 启动失败

Java - 如何创建一副纸牌(重点是静态数组)? - AP计算机科学项目

java - 使用 Spring 的集群 MDB

regex - 查找文件中的数字并使用 perl 更改其值

用于表单验证的正则表达式 1-9999

Java 正则表达式 - 尝试使用正则表达式获取 "function"参数数组

java - 共享所有 Hibernate 实体的公共(public)查询结果

java - x in y 定义在一个不可访问的类或接口(interface)中,ID in structure