2017-08-03 136 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/ 非常有用的,你甚至可以在這個網站