【问题标题】:Extract string between the tags in Java在Java中的标签之间提取字符串
【发布时间】:2018-06-25 11:47:54
【问题描述】:

我有如下字符串

Msg_Begin
Some message1
Msg_End
Msg_Begin
Some message2
Msg_End
Msg_Begin
Some message3
Msg_End

并希望将 Msg_BeginMsg_End 之间的消息放入列表 喜欢

[Some message1, Some message2, Some message3]

Java 中最好的方法是什么。

【问题讨论】:

  • 你认为的方法是什么?
  • 我知道使用 index 和 substring 方法在两个字符串之间提取字符串。但我想不出任何简单的方法来循环和提取字符串。我不想使用正则表达式,因为我在这些概念上很差。

标签: java string parsing text-extraction


【解决方案1】:
String messages = originalString.replaceAll("Msg_Begin","");
String[] array = messages.split("Msg_End");
return Arrays.asList(array);

请确保您的消息不包含Msg_BeginMsg_End

【讨论】:

  • 如果邮件包含\n怎么办?
  • 您实际上也可以在询问之前尝试一下。只需放上断线,看看会发生什么。如果您不想删除中断字符串而不是相应地更改代码。
【解决方案2】:

您可以使用正则表达式来实现:

//Filling Your test case and print
String entry = "Msg_Begin\r\n" + 
               "Some message1\r\n" + 
               "Msg_End\r\n" + 
               "Msg_Begin\r\n" + 
               "Some message2\r\n" + 
               "Msg_End\r\n" + 
               "Msg_Begin\r\n" + 
               "Some message3\r\n" + 
               "Msg_End";

System.out.println("IN : \r\n" + entry) ;

//Compile the regular expression patern, providing the DOTALL flag to enable mutiline matches
Pattern p = Pattern.compile("Msg_Begin\r\n(.+?)\r\nMsg_End(\r\n)?", Pattern.DOTALL) ;  
Matcher m = p.matcher(entry) ; 

// iterate over results (for exemple add them to a list)
System.out.println("\r\nOUT :") ;
List<String> list = new ArrayList<>();
while (m.find()) {
    list.add( m.group(1));
    System.out.println(m.group(1)) ;
}

产生以下结果:

IN : 
Msg_Begin
Some message1
Msg_End
Msg_Begin
Some message2
Msg_End
Msg_Begin
Some message3
Msg_End

OUT :
Some message1
Some message2
Some message3

更多关于正则表达式语法的信息可以找到here

【讨论】:

    猜你喜欢
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多