在引号

时间:2017-08-03 20:39:46

标签: java quotation-marks

这是我正在尝试使用的一段文字:

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>

我正在尝试提取“”之间的coördinates并将“”之间的值放入字符串中,但我无法让它工作......

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

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新手:(

1 个答案:

答案 0 :(得分:0)

我认为以下代码可以解决问题... &#34;字符串&#34;仅用于测试正则表达式

    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);

得到经度,只需在正则表达式中用lon替换lat

此网站对于创建正则表达式非常有用 https://regex101.com/ 你甚至可以在这个网站上创建java代码