拆分一个包含多个特殊字符的字符串 - Java

时间:2016-10-19 07:33:40

标签: java regex string

^((?!PATTERN).)*$

如果给出上面的字符串,则输出应为PATTERN。

每个输入的特殊字符都相同,用户只能更改这些特殊字符内的字词。

当我进行分割时,我会在索引6 Exception附近获得一个未闭合组。

String test = "^((?!PATT).)*$";
String patternOne = "^((?!";
String patternTwo = ").)*$";
if(test.contains(patternOne) && test.contains(patternTwo))
{
  test = test.split(patternOne)[1];
  test = test.split(patternTwo)[0];
}

5 个答案:

答案 0 :(得分:2)

String上的split()方法采用RegEx。您传递的是无效的RegEx。您最好使用substring()函数,因为您已经知道前缀和后缀模式。

test = test.substring(patternOne.length(), test.length() - patternTwo.length());

答案 1 :(得分:1)

  

这不应该是更简单的方法吗?因为你要覆盖你的测试变量,你可以只用你的模式替换你的模式。你根本不需要检查测试是否包含它们

    String test = "^((?!PATT).)*$";
    String patternOne = "^((?!";
    String patternTwo = ").)*$";
    test = test.replace(patternOne, "").replace(patternTwo,"");

答案 2 :(得分:0)

请更改代码:

String test = "^((?!PATT).)*$";
String patternOne = "^((?!";
String patternTwo = ").)*$";
if(test.contains(patternOne) && test.contains(patternTwo))
{
  test = test.split(patternOne)[1];
  test = test.split(patternTwo)[0];
}

这样更容易:

String test ="^((?!PATTERN).)*$";
String  result = test.replaceAll("[^\\w\\s]","");

答案 3 :(得分:0)

您收到错误的原因是split方法将其参数理解为 regex ,并且前缀和后缀中的所有字符实际上都是正则表达式中的特殊字符。

有一些方法可以转义特殊字符,但在这种情况下,实际上不需要使用基于正则表达式的split方法来满足此特定要求。它实际上不是正确的工具。只需使用substring从模式中提取单词,因为您确切知道它的起始位置和结束位置:

class Test {
    public static final String PREFIX = "^((?!";
    public static final int PREFIX_LEN = PREFIX.length();
    public static final String SUFFIX = ").)*$";
    public static final int SUFFIX_LEN = SUFFIX.length();

    public static String extractWord( String arg ) {
        if (arg.startsWith(PREFIX) && arg.endsWith(SUFFIX)) {
            return arg.substring(PREFIX_LEN, arg.length() - SUFFIX_LEN);
        }
        return null;
    }

    public static void main( String[] args ) {
        System.out.println( extractWord("^((?!PATT).)*$") );
    }
}

这告诉它提取在PREFIX结束后开始的字符串部分,并在SUFFIX的开头结束。

答案 4 :(得分:-1)

你可以通过多次分割字符串来实现它

String test = "^((?!PATT).)*$";
String patternOne = "^((?!";
String patternTwo = ").)*$";
if(test.contains(patternOne) && test.contains(patternTwo))
{
  test = test.split(patternOne)[1].split(patternTwo)[0];
}

让我知道这是否有效?

相关问题