如何使用Jsoup删除硬空格?

2022-09-03 18:27:29

我正在尝试删除硬空格(从HTML中的实体中删除)。我不能用或等删除它!我不明白。 .trim().replace(" ", "")

我甚至在Stackoverflow上找到了尝试,但也没有工作。\\u00a0

我试过这个(因为返回实际的硬空格字符,U + 00A0):text()

System.out.println( "'"+fields.get(6).text().replace("\\u00a0", "")+"'" ); //'94,00 '
System.out.println( "'"+fields.get(6).text().replace(" ", "")+"'" ); //'94,00 '
System.out.println( "'"+fields.get(6).text().trim()+"'"); //'94,00 '
System.out.println( "'"+fields.get(6).html().replace(" ", "")+"'"); //'94,00' works

但是我不明白为什么我不能用..text()


答案 1

你的第一次尝试非常接近它,你说得很对,Jsoup映射到U + 00A0。你只是不想在字符串中使用双反斜杠: 

System.out.println( "'"+fields.get(6).text().replace("\u00a0", "")+"'" ); //'94,00'
// Just one ------------------------------------------^

replace不使用正则表达式,因此您不会尝试将文字反斜杠传递到正则表达式级别。您只想在字符串中指定字符 U+00A0。


答案 2

该问题已经过编辑,以反映真正的问题。

新答案;硬空间,即。实体(Unicode 字符 NO-BREAK 空格 U+00A0)在 Java 中可以由代码变为的字符表示,其中字符串是从方法获取的\u00a0,strtext()

str.replaceAll ("\u00a0", "");

旧答案;使用 JSoup 库,

import org.jsoup.parser.Parser;

String str1 = Parser.unescapeEntities("last week, Ovokerie Ogbeta", false);
String str2 = Parser.unescapeEntities("Entered » Here", false);
System.out.println(str1 + " " + str2);

打印输出:

last week, Ovokerie Ogbeta Entered » Here 

推荐