【发布时间】:2020-01-19 15:03:31
【问题描述】:
我有一个字符串,它在另一个双引号内包含双引号。
例如:
输入1:
<span style="font-family: pp-sans-big-light, "Noto Sans", Calibri, Trebuchet, Arial, "sans serif"; font-size: 17px; text-align: start; background-color: rgb(255, 255, 255);" class="transaction" name="details"> How are you</span>
预期输出1:
<span style="font-family: pp-sans-big-light, Noto Sans, Calibri, Trebuchet, Arial, sans serif; font-size: 17px; text-align: start; background-color: rgb(255, 255, 255);" class="transaction" name="details"> How are you</span>
输入 2:
<span title="Conditional (A/B) Content on "Transactions.Recipient Name"" class="transaction" name="details"> Transaction Recipient</span>
预期输出 2:
<span title="Conditional (A/B) Content on Transactions.Recipient Name" class="transaction" name="details"> Transaction Recipient</span>
我尝试了以下选项,
选项 1:
public static void main(String[] args) throws Exception{
int i;
String title = null, style = null, temp = null;
String tempNodeValue = "<?xml version=\"1.0\"?><dummyroot>+/**INPUT_HERE**/+</dummyroot>";
// tempNodeValue = tempNodeValue.replace("\"",""");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new InputSource(new StringReader(tempNodeValue)));
NodeList nodeList = document.getElementsByTagName("span");
for(i=0;i<nodeList.getLength(); i++){
Node node =nodeList.item(i);
if(node.getAttributes().getNamedItem("title") != null){
title = node.getAttributes().getNamedItem("title").getNodeValue();
temp = title.replace("\"","'");
tempNodeValue = tempNodeValue.replace(""","\"");
tempNodeValue = tempNodeValue.replace(title,temp);
}
if(node.getAttributes().getNamedItem("style") != null){
style = node.getAttributes().getNamedItem("style").getNodeValue();
temp = style.replace("\"","'");
tempNodeValue = tempNodeValue.replace(""","\"");
tempNodeValue = tempNodeValue.replace(style,temp);
}
}
System.out.println(tempNodeValue);
}
选项 2:
public static void main(String[] args) throws Exception{
String tempNodeValue = /**INPUT_HERE**/;
tempNodeValue = tempNodeValue.replaceAll("\"(\\b[^\"]+|\\s+)?\"(\\b[^\"]+\\b)?\"([^\"]+\\b|\\s+)?\"","\"$1$2$3\"");
System.out.println(tempNodeValue);
}
我也尝试了 jsoup。但他们都没有工作。选项 2 适用于输入 2,但不适用于输入 1。选项 1 也不起作用。有人可以帮我吗?我浏览了 stackoverflow 中的所有现有答案,但没有一个有帮助。
【问题讨论】:
-
感觉有些情况这里没有描述。你怎么知道哪些报价在其他报价“内部”,而不仅仅是顶级报价?我认为要求不明确。
-
嗨@arcadeblast77,我们在这里考虑的字符串是一个html属性。我想你可以从那一刻开始。因此对于该属性值,我需要保留外部双引号并删除所有内部双引号
-
删除了我的回复,因为它没有捕捉到一些极端情况。我怀疑这个问题可以在我们没有看到的堆栈的一部分中解决,或者通过库来解决。我知道你提到过尝试 jsoup,但我仍然倾向于为此建立一个图书馆。 (如果我知道哪一个,我会发布。)另外,有没有可能这是一个 XY 问题? meta.stackexchange.com/questions/66377/what-is-the-xy-problem
-
为什么会有这个字符串?无效的 HTML 是从哪里来的?
-
@user207421 我们的 webapp 中有一个 aloha 编辑器,它引入了这个无效的 html。
标签: java regex string replace double-quotes