我需要帮助, 我有一个类似
的字符串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());
}
}
感谢您的帮助
答案 0 :(得分: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]);
正则表达式在等号上分裂并消耗它周围的任何空格,因此您不必修剪到零件。
答案 1 :(得分: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)
答案 2 :(得分:0)
String line = "LOCALHOST = https://192.168.56.1";
String []s =line.split("=");
map.put(s[0].trim(), s[1].trim());
答案 3 :(得分:-2)
这非常简单,不需要匹配/模式&#39;正则表达式。试试这个:
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]);