gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:43:04 25 4
gpt4 key购买 nike

我在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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com