-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

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

これは非常に単純で、'matcher/pattern' regex を必要としません。これを試して:

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 に答える