用于获取特定数据的正则表达式

我有一个可以作为文本框阅读的文件,我想只获得之后可用的数据

start =“n = and end =”n =

      

我尝试过以下操作:

  String startTime = readString.replaceAll(".*start=\"n=|\\s.*", "").trim(); String endTime = readString.replaceAll(".*end=\"n=|\\s.*", "").trim(); Log.e("Start Time is :" , startTime); Log.e("endTime Time is :" , endTime); 

它工作正常,只是获取开始时间和结束时间,但它也显示<?xml标签。

我该如何解决?

请在Java中找到下面的解决方案,这适用于包含该字符串的任何数据

  import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main(String[] args) { String inputData1 = ""+ "" + "" + "" + "" + "" + "  " + "" + ""; String inputData2 = "some data goes here with or without tags; ; askjdhfla "; Pattern pattern = Pattern.compile("]*start\\s*=\\s*\"n\\s*=\\s*([^\"]*)\"[^>]*end=\"n\\s*=\\s*([^\"]*)\"[^>]*>"); Matcher matcher = pattern.matcher(inputData1); while(matcher.find()){ System.out.println("start=\"n="+matcher.group(1)+", & end=\"n="+matcher.group(2)+""); } } } Output For InputData1: start="n=10.815s, & end="n=19.914s start="n=10.815s, & end="n=20.914s Output For InputData2: start="n=10.815s, & end="n=20.914s 

我宁愿使用XML解析器来读取它。 正则表达式不适合解析XML / HTML等。您可以在SO中找到许多与此相关的参考资料。

对于Java,DOM和SAX是可能的,但JDOM可能是一个更容易的起点。

我加入了以前的答案。 但是如果你的文件总是很小,只有几个字符串,你可以使用Regexp。 在这种情况下,请尝试以下模式: (\n|\r|.)*end\s*=\s*\"n=(.*)\"(\n|\r|.)*"

UPD:第2组将为您提供您想要的。

它始终是解析器解析xml / html的最佳方法,而不是正则表达式。 但是关于你的问题。 你可以试试以下:

 String s = "foo\n bar\n"; String re = "(?s).*?(?<=start=\"n=)([^\"]*).*"; String startTime=s.replaceAll(re, "$1"); 

上面的例子将给出字符串startTime 10.815s 。 如果你想获得endTime,用(结束)替换re(start)

关于正则表达式的简短解释:

 (?s) is flag dotall, which means, the regex will match new lines as well (?<=start=\"n=)([^\"]*) this is look behind. search for text following start="n= and not "(double quote) in this case is 10.815s 

希望能帮助到你