JAVA中String内的搜索模式

问题描述 投票:0回答:2

我在Java中使用PDFBox,并成功检索了pdf。但是现在我希望搜索一个特定的单词,只检索以下数字。具体来说,我想搜索Tax并检索作为tax的数字。这两个字符串似乎用制表符分隔。

我的代码如下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();
}
java string
2个回答
3
投票

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

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中获得更多的想法。


2
投票

进行此类操作的最佳方法是使用正则表达式。我经常使用this tool编写正则表达式。您的正则表达式可能看起来像:tax\s([0-9]+)。您可以看看this tutorial如何在Java中使用正则表达式。

© www.soinside.com 2019 - 2024. All rights reserved.