【问题标题】:replaceAll not working on escape character XMLreplaceAll 不适用于转义字符 XML
【发布时间】:2018-03-09 10:27:58
【问题描述】:

​ 我正在尝试使用JavaXML 解析为JSONJSON.parse 在这个角色上抛出这个错误:

JSON.parse: bad control character in string literal

我尝试在将这些字符发送到 JSON.parse 之前替换它们,但是这行代码不起作用。有没有更好的方法来完全替换/删除这些字符?

String trim = desc.replaceAll("
", "\\n");

要解析的XML

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod 
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim 
    veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea 
    commodo consequat. Duis aute irure dolor in reprehenderit in voluptate 
    velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint 
    occaecat cupidatat non proident, sunt in culpa qui officia deserunt 
    mollit anim id est laborum.

【问题讨论】:

  • Java 还是 JavaScript?
  • 显然是java。 javascript中没有String trim =
  • @Phix XML > Java > JavaScript
  • 是预期十六进制字符的 html 代码,但 xD 中的 x 不是有效的十六进制数字!
  • “要解析的xml”不是xml,它是包含一些xml实体的文本。你真正想做的是什么? 是一个表示回车的实体。

标签: java json xml parsing


【解决方案1】:

当您展示的示例包含您拥有的完整 XML 输入时,您不是在解析 XML。

假设这是一个片段。您的解决方案只转义一件事,但要获得有效的 JSON,您应该转义 JSON 中不允许的所有字符,否则会导致不需要的行为。因此,寻找可以为您正确转义 JSON 的东西是个好主意:

Java escape JSON String?

【讨论】:

    【解决方案2】:

    想通了:

      public static String cleanDescription(String desc){
    
            String trim = desc.replaceAll("<.*?>", ""); //removes html elements
            //there's a phantom question mark that sometimes gets added to the the front and end of the string
            if(!Character.isLetter(trim.charAt(0))) trim = trim.substring(1, trim.length());
    
            Integer charCount = 0;
            for(int j = 1; j <= 3; j++){
                if(!Character.isLetter(trim.charAt(trim.length() - j)) &&
                        !Character.isDigit(trim.charAt(trim.length() - j))) charCount++;
            }
            if(charCount >= 2) trim = trim.substring(0, trim.length() - (charCount - 1));
    
    
            Pattern pt = Pattern.compile("[^a-zA-Z0-9()\\.\\,]");
            Matcher match= pt.matcher(trim);
            while(match.find())
            {
                String s = match.group();
                trim = trim.replaceAll("\\" + s, " ");
            }
    
            return trim.trim();
        }
    

    【讨论】:

      猜你喜欢
      • 2013-09-22
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多