Java RegEx字符串不包括特定单词

时间:2013-07-27 23:09:55

标签: java regex

UpperCaseConverter 将输入文本转换为大写文本,不包括与regEx “(?i)^((?!sht)匹配的单词。)*”

我期望得到的是 1A0A-50-CRD-140-20002-063484C-N-01_Sht_1A.pdf ,但结果是 的 1A0A-50-CRD-140-20002-063484C-N-01_Sht_1a.pdf

除了.pdf

之外,这封信的最后部分怎么可能是大写

UpperCaseConverter

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

public class UpperCaseConverter {

    private UpperCaseConverter(){};

    public static String convert(String text, String regEx) {
        StringBuilder toBeConverted = new StringBuilder(text);

        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(toBeConverted);

        while(matcher.find()) {
            String buf = toBeConverted.substring(matcher.start(), matcher.end()).toUpperCase();
            toBeConverted.replace(matcher.start(), matcher.end(), buf);
        }

        return toBeConverted.toString();
    }
}

*的测试用例

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

public class UpperCaseConverterTest {

    @Test
    public void testUpperCase() {
        String expect = UpperCaseConverter.convert("1a0A-50-CRD-140-20002-063484C-N-01_Sht_1a.pdf", 
                "(?i)^((?!sht).)*");
        assertEquals("1A0A-50-CRD-140-20002-063484C-N-01_Sht_1A.pdf", expect);
    }
}

1 个答案:

答案 0 :(得分:0)

根据您的指示,您的正则表达式会在最后一次出现“sht”之前停止。只有正则表达式部分才能获得大写处理。