正则表达式操作的优先级 [英] Priority in regex manipulating

查看:133
本文介绍了正则表达式操作的优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些java代码将字符串拆分为字符串数组。首先,我使用正则表达式模式\\,\\,| \\,拆分该字符串,然后使用模式<$ c $进行拆分C> \\,| \\,\\,。为什么第一个输出和第二个输出之间有区别?

I write some java code to split string into array of string. First, I split that string using regex pattern "\\,\\,|\\," and then I split using pattern "\\,|\\,\\,". Why there are difference between output of the first and output of the second?

public class Test2 {
    public static void main(String[] args){

        String regex1 = "\\,\\,|\\,";
        String regex2 = "\\,|\\,\\,"; 

        String a  = "20140608,FT141590Z0LL,0608103611018634TCKJ3301000000018667,3000054789,IDR1742630000001,80507,1000,6012,TCKJ3301,6.00E+12,ID0010015,WADORI PURWANTO,,3000054789";
        String ss[] = a.split(regex1); 

        int index = 0; 
        for(String m : ss){
            System.out.println((index++)+ ": "+m+"|"); 
        }
    }
} 

使用<$ c时的输出$ c> regex1 :

0: 20140608|
1: FT141590Z0LL|
2: 0608103611018634TCKJ3301000000018667|
3: 3000054789|
4: IDR1742630000001|
5: 80507|
6: 1000|
7: 6012|
8: TCKJ3301|
9: 6.00E+12|
10: ID0010015|
11: WADORI PURWANTO|
12: 3000054789|

当使用 regex2 时:

0: 20140608|
1: FT141590Z0LL|
2: 0608103611018634TCKJ3301000000018667|
3: 3000054789|
4: IDR1742630000001|
5: 80507|
6: 1000|
7: 6012|
8: TCKJ3301|
9: 6.00E+12|
10: ID0010015|
11: WADORI PURWANTO|
12: |
13: 3000054789|

在处理这种情况时,我需要解释正则表达式引擎的工作原理。

I need some explanation of how regex engine works when handling this situation.

推荐答案

正则表达式的工作原理:状态机始终从左向右读取。 ,| ,, == ,因为它始终只与第一次轮换相匹配:

How regex works: The state machine always reads from left to right. ,|,, == ,, as it always will only be matched to the first alternation:

img http ://gyazo.com/9fb73ec138449ed2489d7b66f703447d.png

,, |, == ,,?

x http://gyazo.com/f39e53c2fd99e9832b2c04508a988c9f.png

但是,你应该使用 ,,? ,这样就没有回溯:

However, you should use ,,? instead so there's no backtracking:

r http://gyazo.com/d06516c7d2cdf5dd4c1e65886dbaf281.png

这篇关于正则表达式操作的优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆