gpt4 book ai didi

java - 获取出现在 2 个或更多空格后的字符的正则表达式

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:36:25 27 4
gpt4 key购买 nike

我正在尝试对收据进行 OCR 识别并读取行项目。因此,在获得订单项后,我想获得带有货币符号的项目价格。

CHOC. ORANGE   x           £1.00

我试图用井号分隔文本,但有时 OCR 会将井号误认为其他字符。

那么正则表达式中有没有一种方法可以从行尾读取字符并在遇到大于 3 的空格时停止?还是我必须编写自定义算法?

我试图从行尾获取最后一个单词,但遇到标点符号或空格时也会失败。

\b(\w+)$  

最佳答案

在正则表达式中,您使用量词 来指定匹配模式的出现次数。对于两个或更多空白字符,正则表达式为 \s{2,}

对于您的问题,您还需要做好准备,英镑符号可能会或可能不会被正确识别。所以,我会使用 | 来表达备选方案。

下面的程序给出了一个如何做到这一点的例子:

import java.util.Currency;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexReceiptOcr {

public static void main(String[] args) {
// String poundSymbol = Currency.getInstance(Locale.UK).getSymbol();
String poundSymbol = "£";
String[] inputStrings = {
"CHOC. ORANGE x " + poundSymbol + "1.00"
, "CHOC. ORANGE x L1.00"
};

String regex = "(?<description>.+)"
+ "\\s{2,}" // two or more white space
+ "(?<currency>"+poundSymbol+"|\\w)" // Pound symbol may be mis-reaad
+ "(?<amount>\\d+\\.\\d{2})";
Pattern p = Pattern.compile(regex);
for (String inputString : inputStrings) {
Matcher m = p.matcher(inputString);
if (m.find()) {
String description = m.group("description");
String currency = m.group("currency");
String amountString = m.group("amount");

System.out.format("Desciption: %s%n"
+ "Currency: %s%n"
+ "Amount: %s%n"
, description.trim()
, currency
, amountString);
}
}
}

}

输出是这样的:

Desciption: CHOC. ORANGE    x
Currency: £
Amount: 1.00
Desciption: CHOC. ORANGE x
Currency: L
Amount: 1.00

关于java - 获取出现在 2 个或更多空格后的字符的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41528851/

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