java - JAVA 中字符串中的搜索模式

标签 java regex string

我在java中使用PDFBox并成功检索了pdf。但现在我希望搜索特定的单词并只检索以下数字。具体来说,我想搜索税并检索税的号码。这两个字符串似乎由制表符分隔。

我的代码如下 atm

  File file = new File("yes.pdf");
try {
     PDDocument document = PDDocument.load(file);
     PDFTextStripper pdfStripper = new PDFTextStripper();

String text = pdfStripper.getText(document);

System.out.println(text);

// search for the word tax
// retrieve the number af the word "Tax"

document.close();
}

最佳答案

我在我的项目中使用过类似的东西。希望对您有帮助。

public class ExtractNumber {

public static void main(String[] args) throws IOException { 
    PDDocument doc = PDDocument.load(new File("yourFile location"));

    PDFTextStripper stripper = new PDFTextStripper();
    List<String> digitList = new ArrayList<String>();

    //Read Text from pdf 
    String string = stripper.getText(doc);

    // numbers follow by string
    Pattern mainPattern = Pattern.compile("[a-zA-Z]\\d+");

    //Provide actual text
    Matcher mainMatcher = mainPattern.matcher(string);
    while (mainMatcher.find()) {
        //Get only numbers
        Pattern subPattern = Pattern.compile("\\d+");
        String subText = mainMatcher.group();
        Matcher subMatcher = subPattern.matcher(subText);
        subMatcher.find();
        digitList.add(subMatcher.group());
    }

    if (doc != null) {
        doc.close();
    }

    if(digitList != null && digitList.size() > 0 ) {
        for(String digit: digitList) {
            System.out.println(digit);
        }
    }
}

}

正则表达式[a-zA-Z]\d+从pdf文本中查找一个或多个数字,后跟一个数字。

\d+ 表达式从上述模式中查找特定文本。

您还可以使用不同的正则表达式来查找特定的位数。

您可以从this tutorial获得更多想法.

关于java - JAVA 中字符串中的搜索模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59138223/

相关文章:

java - Imap 文件夹共享邮箱 - 在无效状态下收到 BAD 命令

javascript - 试图让正则表达式从 camelCase 和 CamelCase 中识别和提取单词

c# - 使用多个正则表达式命令解析消息时的性能问题

java - 为什么添加5个对象后这个集合的大小是1?

java - 多语言数据库,默认回退

java - 正则表达式将字符串转换为 json 数组

c# - 在 C# 中根据输入对字符串进行分类

java - 字符串范围 : regular heap vs pool

c - 输出额外字符的简单字符加密

java - LinkedHashMap.removeEldestEntry 有什么用?