Java toUpperCase()和RegEx问题

时间:2011-08-25 15:59:18

标签: java regex

好的我有一个我正在解析的字符串,我需要在该字符串上使用toUpperCase()。之后我使用Java RegExp。问题是由于某种原因,Java的String toUpperCase()正在修改空格,而我的RegExp将不起作用。

有没有办法告诉toUpperCase()忽略空格?或者也许可以在RegExp中处理它?<​​/ p>

下面是我用来解决这个问题的代码。如果我取消注释下面的toUpperCase()行,我的RegExp将无效!

    String regExp = "([t][o][k][e][n][\\s]*[=][\\s]*)";
    String content = "The token ='testing'" ;

    //content = content.toUpperCase();  //uncomment this and RegExp will break!!!

    Pattern pattern = Pattern.compile(regExp);
    Matcher matcher = pattern.matcher(content);

    if(matcher.find()){
        int startIndex= matcher.start(1);
        int endIndex = matcher.end(1);

        String posStartExpression = content.substring(startIndex,endIndex);
        System.out.println(posStartExpression);
    }

1 个答案:

答案 0 :(得分:3)

您遇到此行为是因为您的正则表达式区分大小写。

试试这个:

Pattern.compile(regExp, Pattern.CASE_INSENSITIVE);