-2

我需要帮助,我有一个类似的字符串

LOCALHOST = https://192.168.56.1

我想获取“LOCALHOST”和 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());
    }
}

感谢您的帮助

4

4 回答 4

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

正则表达式在等号上拆分并占用它周围的任何空间,因此您不必修剪到部分。

于 2013-08-26T22:00:55.857 回答
0

尝试以下操作:

final Matcher m = Pattern.compile("^(.+) = https:\\/\\/(\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})$");
m.matcher(line);
final Map<String,String> map = new HashMap<String,String();       
if (m.matches())
{
   final String lh = m.group(1);
   final String ip = m.group(2);
   map.add(lh,ip);
}

学习使用一个好的交互式正则表达式编辑器,比如regex101.com上的那个

/^(.+) = https:\/\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/m
^ Start of line
1st Capturing group (.+) 
. 1 to infinite times [greedy] Any character (except newline)
 = https:\/\/ Literal  = https://
2nd Capturing group (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) 
\d 1 to 3 times [greedy] Digit [0-9]
\. Literal .
\d 1 to 3 times [greedy] Digit [0-9]
\. Literal .
\d 1 to 3 times [greedy] Digit [0-9]
\. Literal .
\d 1 to 3 times [greedy] Digit [0-9]
$ End of line
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
于 2013-08-26T21:49:56.093 回答
0
String line = "LOCALHOST = https://192.168.56.1";

String []s =line.split("=");
map.put(s[0].trim(), s[1].trim());
于 2013-08-26T21:51:30.657 回答
-2

这非常简单,不需要“匹配器/模式”正则表达式。试试这个:

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]);
于 2013-08-26T21:55:31.957 回答