2017-08-03 95 views
0

这里有一段文字我想一起工作:阅读文本

lat="52.336575" lon="6.381008">< time>2016-12-19T12:12:27Z< /time>< name>Foto 8 </name>< desc>Dag 4 E&amp;F 
Geb 1.4 
Hakhoutstoof < /desc>< /wpt> 

我想要的“之间抽取坐标”,并把之间的值“变成了”串,但我不能得到它的工作...

这里是我的代码(到目前为止):

public void openFile() { 
    Chooser = new JFileChooser("C:\\Users\\danie\\Desktop\\"); 
    Chooser.setAcceptAllFileFilterUsed(false); 
    Chooser.setDialogTitle("Open file"); 
    Chooser.addChoosableFileFilter(new FileNameExtensionFilter("*.gpx", 
    "gpx")); 
    int returnVal = Chooser.showOpenDialog(null); 

    try { 
     Dummy = new Scanner(Chooser.getSelectedFile()); 
    } catch (FileNotFoundException E) { 
     System.out.println("Error: " + E); 
    } 
} 

public void createDummy() { 
    Dummy.useDelimiter("<wpt"); 
    if (Dummy.hasNext()) { 
     String Meta = Dummy.next(); 
    } 
    Dummy.useDelimiter("\\s[<wpt]\\s|\\s[</wpt>]\\s"); 
    try { 
     while (Dummy.hasNext()) { 
      String Test = Dummy.next(); 
      DummyFile = new File("Dummy.txt"); 
      Output = new PrintWriter(DummyFile); 
      Output.print(Test); 
      Output.println(); 
      Output.flush(); 
      Output.close();   
     } 

     Reader = new FileReader(DummyFile); 
     Buffer = new BufferedReader(Reader); 
     TestFile = new File("C:\\Users\\danie\\Desktop\\Test.txt"); 
     Writer = new PrintWriter(TestFile); 
     String Final; 
     while ((Final = Buffer.readLine()) != null) { 
      String WPTS[] = Final.split("<wpt"); 
      for (String STD:WPTS) { 
       Writer.println(STD); 
       Writer.flush(); 
       Writer.close(); 
      }    
     } 

    } catch (IOException EXE) { 
     System.out.println("Error: " + EXE); 
    } 
    Dummy.close(); 
    } 
} 

我真的对Java :(

+0

创建Java代码中看到了这个问题,它应该指向你在正确的方向:https://stackoverflow.com/questions/1473155/how java中的数据引用之间的数据 –

+0

阅读有关组的正则表达式,这应该以一种简洁的方式来实现。并使用[Regex101](http://regex101.com)来测试你的模式。 – SHG

+2

该文本看起来非常接近XML。如果是,应该使用XML解析器解析,而不是使用正则表达式。 – Andreas

回答

0

我认为下面的代码就可以了...... 的“串”仅用于测试正则表达式

final String string = "lat=\"52.336575\" lon=\"6.381008\">< time>2016-12-19T12:12:27Z< /time>< name>Foto 8 </name>< desc>Dag 4 E&amp;F \nGeb 1.4 \n" + "Hakhoutstoof < /desc>< /wpt>"; 

    final String latitudeRegex = "(?<=lat=\")[0-9]+\\.[0-9]*"; 
    final Pattern latitudePattern = Pattern.compile(latitudeRegex); 
    final Matcher latitudeMatcher = latitudePattern.matcher(string); 

    //finds the next (in this case first) subsequence matching the given regex 
    latitudeMatcher.find(); 
    String latitudeString = latitudeMatcher.group(); 
    double lat = Double.parseDouble(latitudeString); //group returns the match matched by previous match 
    System.out.println("lat: " + lat); 

得到经度,只是在正则表达式

这种替代纬度的经度网站是创建一个正则表达式 https://regex101.com/ 非常有用的,你甚至可以在这个网站