我有以下字符串:提取子串從主字符串的屬性和值在JAVA
\018attribute1=value1\028attribute2=value2\033attribute3=value3
注:的"\0xx"
是硬字符串沒有特殊字符包括和"\0xx"
是隨機的。我從api得到這個字符串,它包含「\」字符。
我想提取屬性名稱和屬性值
怎麼辦?
我有以下字符串:提取子串從主字符串的屬性和值在JAVA
\018attribute1=value1\028attribute2=value2\033attribute3=value3
注:的"\0xx"
是硬字符串沒有特殊字符包括和"\0xx"
是隨機的。我從api得到這個字符串,它包含「\」字符。
我想提取屬性名稱和屬性值
怎麼辦?
您需要兩次跳過\
個字符。一次用於Java,一次用於正則表達式。這將它變成\\\\
。然後你可以使用Pattern
和Matcher
建立映射你的價值觀的:
Pattern p = Pattern.compile("\\\\0..([^=]+)=([^\\\\]*)");
Matcher matcher = p.matcher("\\018attribute1=value1\\028attribute2=value2\\033attribute3=value3");
Map<String, String> attributes = new HashMap<String, String>();
while (matcher.find()) {
attributes.put(matcher.group(1), matcher.group(2));
}
的東西,像這樣的工作對我來說:
String str = "\\018attribute1=value1\\028attribute2=value2\\033attribute3=value3";
Pattern p = Pattern.compile("0\\d{2}(.*?)=(.*?)(\\\\|$)");
Matcher m = p.matcher(str);
while(m.find())
{
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println("-------");
}
它得到:
attribute1
value1
-------
attribute2
value2
-------
attribute3
value3
的正則表達式假定你需要匹配的模式總是以反斜線後跟2個數字(\ 0x X)。然後它會提取第一個子字符串,直到遇到等號。一旦匹配等號,它將繼續匹配,直到它碰到另一個斜線或者字符串的結尾。
如果你沒有這三位數字,你可以用\0\w{2}
這行代替它,它會匹配一個零,後面跟着任何一個字母,數字或下劃線。
不,這個問題是關於特殊字符「\」 – MOHAMED