有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

条件正则表达式使用Java匹配文本输入流中的组,忽略格式错误的行

在练习了regex tester之后,我发现以下模式[a-zA-Z+[^ \t]+0-9]能够匹配我感兴趣的组:

enter image description here

我试着用如下方式“Java化”它:Pattern.compile("(a-zA-Z)( \t)(0-9)");,不确定这是不是正确的方式。。。但稍后会有更多关于这方面的内容

我的输入流如下所示:

#### LOGS ####
CONSOLE:
makePush            2196
makePush            638
makePush            470
opAdd           8342
opAdd           288
opStop          133
0x
DEBUG:
#### TRACE ####
PUSH32          pc=00000000 gas=10000000000 cost=3

PUSH32          pc=00000033 gas=9999999997 cost=3
Stack:
00000000  0000000000000000000000000000000000000000000000000000000000000005

PUSH32          pc=00000066 gas=9999999994 cost=3
Stack:
00000000  0000000000000000000000000000000000000000000000000000000000000005
00000001  0000000000000000000000000000000000000000000000000000000000000005

ADD             pc=00000099 gas=9999999991 cost=3
Stack:
00000000  0000000000000000000000000000000000000000000000000000000000000005
00000001  0000000000000000000000000000000000000000000000000000000000000005
00000002  0000000000000000000000000000000000000000000000000000000000000005

ADD             pc=00000100 gas=9999999988 cost=3
Stack:
00000000  000000000000000000000000000000000000000000000000000000000000000a
00000001  0000000000000000000000000000000000000000000000000000000000000005

STOP            pc=00000101 gas=9999999985 cost=0
Stack:
00000000  000000000000000000000000000000000000000000000000000000000000000f

因此,我不仅要匹配大空格前后的两个不同部分的行(实际上是三个连续的制表符),而且我还要忽略不符合该模式的每一行,即“^{,“^{,“^{

我试着这样做:

for (String k : debugOutput) {
    Pattern pattern = Pattern.compile("(a-zA-Z)( \t)(0-9)");
    Matcher matcher = pattern.matcher(k);
    while (matcher.find()) {
        System.out.println("group 1: " + matcher.group(1));
        System.out.println("group 2: " + matcher.group(2));
        System.out.println("group 3: " + matcher.group(3));
    }
}

但这是行不通的——它不会吸引我想要的群体,也不会忽视我试图避免的台词


共 (1) 个答案

  1. # 1 楼答案

    将模式更改为:

    Pattern pattern = Pattern.compile("([a-zA-Z]+)(\\s+)([0-9]+)");
    

    如果输入行等于

    String input = "makePush            2196";
    

    它会打印

    group 1: makePush
    group 2:             
    group 3: 2196