我正在尝试使用java在文件中查找和替换但无法获得解决方案。
文件内容
“ProductCode”=“8:{3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5}”
“ProductCode”=“8:.NETFramework,Version = v4.5”
我必须更新第一个 3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5
的指南String line = "\"ProductCode\" = \"8:{3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5}\"";
String pattern = "[\"]([P][r][o][d][u][c][t][C][o][d][e]).+([\"])(\\s)[\"][8][:][{]";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
System.out.println(m.matches());
我变得虚假。
请尽可能提供解决方案。
提前致谢。
答案 0 :(得分:3)
<强>&#34;产品代码&#34; =&#34; 8:{3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5}&#34; 这是以下形式:
quote + ProductCode + quote + whitespace + equals + whitespace +
quote + number + colon + any + quote
一个简单的正则表达式是\"ProductCode\"\s*=\s*\"\d:(.+)\"
当我们将其转义为Java字符串时,我们得到\\\"ProductCode\\\"\\s*=\\s*\\\"\\d:(.+)\\\"
答案 1 :(得分:1)
尝试这种模式:
String pattern = "^\\\"(ProductCode)\\\"\\s\\=\\s\\\"\\w\\:\\{(\\w+\\-*\\w+\\-\\w+\\-\\w+\\-\\w+)\\}\\\"$";
答案 2 :(得分:0)
使用正则表达式解决这个问题就像拿一把大锤打破一个坚果。相当简单:
final String line = "\"ProductCode\" = \"8:{3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5}\"";
final String prefix = "\"ProductCode\" = \"8:{";
final int prefixIndex = line.indexOf(prefix);
final String suffix = "}\"";
final int suffixIndex = line.indexOf(suffix);
final String guid = line.substring(prefixIndex + prefix.length(), suffixIndex);