【问题标题】:Java Regex complex ID expression filteringJava Regex 复杂 ID 表达式过滤
【发布时间】:2018-05-21 10:12:56
【问题描述】:

我正在使用 Java 实现 PDF 到纯文本的转换。现在我面临着从文本的字符串表示中过滤掉 ID 表达式的问题。

这里的想法是将 ID 捕获为长度仅大于 4 的整个单词并将其删除。 ID 必须以任意顺序同时包含字母和数字。它们可以具有可选的特殊符号,例如 :.- 并且通常都是大写的,除了一些可能只有一个并且(目前)恰好是一个小写字母的情况。 ID 可以在句子中的任何位置遇到,并且在 String 中存在多个句子。我还试图捕获前面的空格(如果有的话),所以在我删除 ID 后没有双空格。如果表达式太复杂,可以将表达式分成几部分。

我创建了一个小型测试 sn-p 来准确显示需要和不需要被正则表达式捕获的内容,并显示我到目前为止的进度。我正在使用标准的 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,遗憾的是我都无法正常工作。我还怀疑在我的示例中使用 [] 是完全不正确的,但这是我现在设法使其(大部分)工作的唯一方法。请帮帮我。

【问题讨论】:

  • 我目前使用的解决方法是将最小长度设置为 6 而不是 4,这似乎可以正确处理除 (DLCS) 和 781-338-3000 之外的所有内容。尽管如此,这远不是一个合适的解决方案,必须改变。

标签: java regex string filter filtering


【解决方案1】:

我和我的同事能够以一种优雅的方式解决这个问题。下面是我当前解决方案中的一个 sn-p。我希望有一天这对某人有用。

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多