String.Replace 来自 ItextSharp 的数据

String.Replace on data from ItextSharp

我正在使用 ItextSharp 从 pdf 中读取数据。检查生成的字符串看起来是正确的,但是 string.Replace 无法替换文本。

因此,我猜这是某种编码问题,但我无法确定。

我从 PDF 导入文本的代码应该转换为 UTF8

 PdfReader pdfReader = new PdfReader("file.pdf");

                for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                    string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

                    currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                    text.AppendLine(currentText);
                }
                pdfReader.Close();

然后我尝试将三个连字符和一个 space (-- -) 替换为仅 3 个连字符 (---)

input = input.Replace("-- -­", "---");

从 PDF 导入中删除 utf8 转换没有任何区别(请参见下面的屏幕截图 - 替换函数后的断点,但文本仍然存在):

编辑:

这里是一个link到一个sample file。在记事本或++中打开时,它会显示一系列 space 和连字符(请参见带有白色 space 渲染的 npp 屏幕截图)。但是,在 c# 中读取时,此文件不会被解释为 unicode 连字符和 Unicode space。

事实证明,ITextSharp 或源 PDF 使用一种称为软连字符的东西来表示标准连字符,因此记事本、notepad++ 和 Visual studio 文本可视化工具都将软连字符呈现为标准连字符, 它们不是同一个字符,这就是 String.Replace 不执行任何替换的原因。

根据我对软连字符的理解,in 通常不应呈现,这在尝试将字符粘贴到网络浏览器或其他程序(例如 charmap)或什至 visual studio 本身时会导致奇怪的行为.

这导致了以下工作代码:

input = input.Replace("­­ ­", "---");

在 Firefox 上,这呈现为用三个连字符替换 space,但是粘贴到记事本显示中(这显示了我的真实意图)。

input = input.Replace("-- -", "---");

https://en.wikipedia.org/wiki/Soft_hyphen

软连字符: http://www.fileformat.info/info/unicode/char/ad/index.htm

连字符(标准连字符) http://www.fileformat.info/info/unicode/char/2010/index.htm

我的解决方案是添加以下行:

        input = input.Replace((char)173, '-');

tl;博士: 字符编码绝对没问题,并非所有连字符都相等。