有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

正则表达式如何在java中查找字符串中的长双精度数

我试图提取文本文件中每一行中存在的端到端延迟值。我使用正则表达式只获取每行末尾的数字,但正则表达式的错误是:

illegal escape character

此外,我需要打开文件来获取每一行,提取结束延迟值,并将其存储在另一个文本文件中(所有提取的结束延迟)

这是我的代码:

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import javax.swing.filechooser.FileSystemView;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author DevAdmin
 */
public class extarctor {

    public static final String s_example = "sender id: 116/sequence number: 117/depth: 443/sending time: 4/23/2020 2:08:54 AM/data: Hello I am SN: 116 this is event # 117 from my sideEnd-End Delay is:2.74550137092987E-05delay registered @ Sink: 621.932901880787";

    public static void main(String[] args) throws IOException {
        //text file, should be opening in default text editor
        File file = new File(FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath()+ "/res/End-End-Delay.txt");

        //first check if Desktop is supported by Platform or not
        if(!Desktop.isDesktopSupported()){
            System.out.println("Desktop is not supported");
            return;
        }

        Desktop desktop = Desktop.getDesktop();
        if(file.exists()) System.out.println("Good, keep going!");

        System.out.println(s_example.matches("\d+\.\d+$"));



    }


}

共 (1) 个答案

  1. # 1 楼答案

    使用Matcher::group提取所需的数字

    演示:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Main {
        public static void main(String[] args) {
            String s_example = "sender id: 116/sequence number: 117/depth: 443/sending time: 4/23/2020 2:08:54 AM/data: Hello I am SN: 116 this is event # 117 from my sideEnd-End Delay is:2.74550137092987E-05delay registered @ Sink: 621.932901880787";
    
            Pattern pattern = Pattern.compile("\\d+.\\d+$");
            Matcher matcher = pattern.matcher(s_example);
            while (matcher.find()) {
                System.out.println(matcher.group());
            }
        }
    }
    

    输出:

    621.932901880787