我使用Java实现PDF到纯文本转换。现在我面临的问题是从文本的String表示中过滤出ID表达式。
这里的想法是将ID作为长度仅大于4的整个单词捕获并删除它们。 ID必须以任何顺序同时包含字母和数字。它们可以有可选的特殊符号,例如:.-并且通常都是大写的,除了几种情况,可能有一个和(现在)只有一个小写字母。可以在句子中的任何位置遇到ID,并且String内有多个句子。我也试图捕获前面的空格(如果有的话),所以删除ID后没有双重空格。如果表达式太复杂,可以将表达式拆分成几个部分。
我已经创建了一个小的测试代码段,以准确显示正则表达式需要捕获的内容,并显示我到目前为止的进度。我正在使用标准的java.util.regex包来实现。
String testString = "Remove this (ACTDIK002), ACTDIK002, (L1:3.CI), 9-12.CT.d.12, and 1A-CS-01 "
+ "but not (DLCS), 781-338-3000, (DTC), (200), K-12, K or 12. "
+ "Also not (), A.I., AI, A or a. . ...";
System.out.println(testString);
String regex = "[\\s]{0,1}[[A-Z]+[\\d]+[-:\\(\\)\\.]*]{4,}[a-z]{0,1}[\\d\\.]*";
//"[\\s]{0,1}[[A-Z]+[\\d]+[-:\\(\\)\\.]*]{4,}[[a-z]{0,1}[\\d\\.]+]*" //for comma removal
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(testString);
testString = matcher.replaceAll("*");
System.out.println(testString);
可能有必要将ID与逗号一起删除,因此如果修改后的表达式能够捕获逗号或通过我提供的备用正则表达式之类的小改动省略它们,那将会很棒。
我目前的解决方案会过滤掉所有需要过滤的内容,但也会过滤掉大部分不应该过滤的内容。似乎规则必须至少有一个大写字母和单词中的一个数字不起作用,可能是因为我需要使用Lookahead / Lookbehind / Grouping,遗憾的是我没有设法正常工作。我也怀疑在我的例子中使用[]是完全错误的,但这是我设法让它(大部分)现在工作的唯一方法。请帮帮我。
答案 0 :(得分:0)
我的同事和我能够以优雅的方式解决这个问题。以下是我当前解决方案的片段。我希望有一天这对某人有用。
String testString = "Remove this (ACTDIK002), ACTDIK002, (L1:3.CI), 9-12.CT.d.12, and 1A-CS-01 "
+ "but not (DLCS), 781-338-3000, (DTC), (200), K-12, K or 12. "
+ "Also not (), A.I., AI, A or a. . ...";
System.out.println(testString);
String regex = "(?i)(?=[\\dA-Z\\(\\)\\.:-]*\\d)(?=[\\dA-Z\\(\\)\\.:-]*[A-Z])[\\dA-Z\\(\\)\\.:-]{5,}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(testString);
testString = matcher.replaceAll("");
System.out.println(testString);
//Clean-up extra spaces and unneeded commas
//testString = testString.replaceAll("\\s{2,}", " ").replaceAll("(\\s\\.)|(\\s\\,)", "");
testString = testString.replaceAll("[ ]{2,}", " ").replaceAll("([ ]\\.)|([ ]\\,)", "");
System.out.println(testString);