RegEx正在使用Perl在线工具但不能在Java中工作

时间:2016-12-12 15:10:37

标签: java regex

我使用online tool创建了一个在perl脚本上运行的RegEx,以下正则表达式为:

^BC1E_SENBR_IC601_FAPM_EN_ID(?:\.?\d\.?)(?:\.?\d\.?)(?:\.?\d\.?)(?:\.?\d\.?)_(?:\.?\w*\.?\.?\w*.?)_(?:\.?\w*\.?\.?\w*\.?).ASC$

我已经编码从sourcePatternStr1变量

生成它

完全匹配以下匹配:

BC1E_SENBR_IC601_FAPM_EN_ID7777_zb0.9961821020403842np_zb0.9961821020403842np.ASC

下面是以下java程序,它没有给出预期的结果。

package com.att.tdms.test;

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

public class Test1 {

    public static void main(String[] args) {

        String sourceStr = "BC1E_SENBR_IC601_FAPM_EN_ID7777_zb0.9961821020403842np_zb0.9961821020403842np.ASC";
        String sourcePatternStr1 = "BC1E_SENBR_IC601_FAPM_EN_ID????_*_*.ASC";

        String destinPatternStr0 = "BC1E_SENBR_IC1601_FAPM_ID<1><2><3><4>_<5>_<6>.ASC";

        StringBuffer sourceRegEx = new StringBuffer(sourcePatternStr1);

        for(int i=sourcePatternStr1.length()-1; i>=0;i --){
            if(sourcePatternStr1.charAt(i) == '?'){

                sourceRegEx.replace(i, i+1, ("(?:\\\\.?\\\\d\\\\.?)"));
            }

            if(sourcePatternStr1.charAt(i) == '*'){

                sourceRegEx.replace(i, i+1, "(?:\\\\.?\\\\w*\\\\.?\\\\.?\\\\w*\\\\.?)");
            }
        }

        System.out.println(sourceRegEx); //BC1E_SENBR_IC601_FAPM_EN_ID(?:\\.?\\d\\.?)(?:\\.?\\d\\.?)(?:\\.?\\d\\.?)(?:\\.?\\d\\.?)_(?:\\.?\\w*\\.?\\.?\\w*\\.?)_(?:\\.?\\w*\\.?\\.?\\w*\\.?).ASC

        Matcher m9 = Pattern.compile(sourceRegEx.toString()).matcher(sourceStr);

        StringBuffer result2 = new StringBuffer(); // We'll build the updated copy here

        while (m9.find())
        {
            String matchedText = m9.group();
            int matchedFrom = m9.start();
            int matchedTo = m9.end();   
            System.out.println("matched [" + matchedText + "] " +
                    "from " + matchedFrom +
                    " to " + matchedTo + ".");
        }

    }

}

我期待将其视为:

matched [7] from 26 to 28
matched [7] from 27 to 29
matched [7] from 29 to 30
matched [7] from 30 to 31
matched [7] from 26 to 28
matched [zb0.9961821020403842np] from 32 to 54
matched [zb0.9961821020403842np] from 55 to 75

任何人都可以帮助我,为什么不能从java代码中匹配,因为它在perl脚本中工作正常。

0 个答案:

没有答案