从字符串中搜索文本并提取其他内容

时间:2013-12-02 16:01:19

标签: java search pattern-matching

我有一个字符串

  

InsertedTextAry NO AGREEMENT EXISTS FOR AGENCY - ABCD< 102354这是测试<

现在的要求是查看文字:

  

没有协议的协议

...存在于上述文本中,如果存在,则提取文本:

  

没有代理协议 - XXXX

NO AGREEMENT EXISTS FOR AGENCY -之后和<之前的部分可以是由数字和/或字母组成的任意长度。

我用代码

完成了搜索
protected void testMethod(String text){
    if(Pattern.matches(APPEND_FIRST + "NO AGREEMENT EXISTS FOR AGENCY" + APPEND_LAST, text)){
        // do something
    }
}

现在我需要一些关于如何提取模式的帮助NO AGREEMENT EXISTS FOR AGENCY - XXXX(其中XXXX - 可以是任意长度的字母数字,后跟<)。

4 个答案:

答案 0 :(得分:1)

public static void main(String[] args) {
    final String TEST = "InsertedTextAry NO AGREEMENT EXISTS FOR AGENCY - ABCD< 102354 This is test<";
      // Create a Pattern object
    Pattern r = Pattern.compile("NO AGREEMENT EXISTS FOR AGENCY[^<]*");
    if(TEST.contains("NO AGREEMENT EXISTS FOR AGENCY"))
    {
          // Now create matcher object.
          Matcher m = r.matcher(TEST);
          if (m.find( )) {
             System.out.println("Found value: " + m.group(0) );
    }
}

输出:

Found value: NO AGREEMENT EXISTS FOR AGENCY - ABCD

答案 1 :(得分:0)

试试这个

String text = "InsertedTextAry NO AGREEMENT EXISTS FOR AGENCY - ABCD< 102354 This is test<";
String pattern1 = "NO AGREEMENT EXISTS FOR AGENCY";
String pattern2 = "<";
if (text.indexOf(pattern1) > -1){
    String value = text.substring(text.indexOf(pattern1));
    value = value.substring(0, value.indexOf(pattern2));
    System.out.println(value);
}

答案 2 :(得分:0)

这个骂人的工作:

public static void main(String[] args) {
    String str = "InsertedTextAry NO AGREEMENT EXISTS FOR AGENCY - ABCD< 102354 This is test<";
    Pattern pattern = Pattern.compile("^.*(NO AGREEMENT EXISTS FOR AGENCY - .*)< (.*)$");
    Matcher m = pattern.matcher(str);
    if (m.find()) {
        System.out.println(m.group(1));
    }
}

此代码打印:

NO AGREEMENT EXISTS FOR AGENCY - ABCD

通过在组中使用regexp,您可以提取所需消息的任何部分

答案 3 :(得分:0)

您可以执行以下操作:

String text = "InsertedTextAry NO AGREEMENT EXISTS FOR AGENCY - ABCD< 102354 This is test<";
    String[] arr = text.split("<")";
    if (arr != null && arr.length > 0) {
         String answer = arr[0].substring(arr[0].indexOf("NO AGREEMENT EXISTS FOR AGENCY"));
    }

回答:“没有协议代理协议 - ABCD”