Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用正则表达式获取两个特定单词并将其保存到HashMap_Java_Regex_String - Fatal编程技术网

Java 使用正则表达式获取两个特定单词并将其保存到HashMap

Java 使用正则表达式获取两个特定单词并将其保存到HashMap,java,regex,string,Java,Regex,String,我需要帮助, 我有一根像 LOCALHOST = https://192.168.56.1 我想获取本地主机和IP地址,然后将其保存到HashMap 这是我到目前为止的代码,我不知道如何使用正则表达式,请帮助 我想要的输出是HashMap{LOCALHOST=192.168.56.1} public static void main(String[] args) { try { String line = "LOCALHOST = https://192.168.56.

我需要帮助, 我有一根像

LOCALHOST = https://192.168.56.1
我想获取本地主机和IP地址,然后将其保存到HashMap

这是我到目前为止的代码,我不知道如何使用正则表达式,请帮助 我想要的输出是HashMap{LOCALHOST=192.168.56.1}

public static void main(String[] args) {
    try {
        String line = "LOCALHOST = https://192.168.56.1";
        //this should be a hash map
        ArrayList<String> urls = new ArrayList<String>();

        //didnt know how to get two string
        Matcher m = Pattern.compile("([^ =]+)").matcher(line);       
        while (m.find()) {
            urls.add(m.group());      
        }

        System.out.println(urls);
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
}
感谢您的帮助

尝试以下方法:
这非常简单,不需要“matcher/pattern”正则表达式。试试这个:

HashMap<String, String> x = new HashMap<String, String>();

String line = "LOCALHOST = https://192.168.56.1";

String[] items = line.split("=");

x.add(items[0], items[1]);

按照标题回答问题:

String line = "LOCALHOST = https://192.168.56.1";
Map<String, String> map = new HashMap<String, String>();
String[] parts = line.split(" *= *");
map.put(parts[0], parts[1]);

正则表达式在等号上拆分,并消耗其周围的所有空格,因此您不必修剪为部分。

问题是什么?运行该代码时得到了什么输出?输出是:LOCALHOST,我不知道如何获取LOCALHOST和IP并将其作为key和object保存到hashmap使用此regexp,您应该获取LOCALHOST和https://192.168.56.1. 你的问题到底是什么?在HashMap中的插入?或者您想要一个regexp来获取没有http://的IP地址吗?您想要一个映射还是一个列表?你在标题和代码中提到hashmap,但你创建了一个列表。我的意思是它没有使用'matcher/pattern'正则表达式。
String line = "LOCALHOST = https://192.168.56.1";

String []s =line.split("=");
map.put(s[0].trim(), s[1].trim());
HashMap<String, String> x = new HashMap<String, String>();

String line = "LOCALHOST = https://192.168.56.1";

String[] items = line.split("=");

x.add(items[0], items[1]);
String line = "LOCALHOST = https://192.168.56.1";
Map<String, String> map = new HashMap<String, String>();
String[] parts = line.split(" *= *");
map.put(parts[0], parts[1]);