[英]How to use Regular Expression in Java
我需要這樣的字符串:
C-USD10.00_FRIES AND BURGUER_USD15.00
在這樣的團體中
segment = first_char;
subtotal_currency = after-next_3_chars;
subtotal = digits_up_to_;
description = text_up_to_;
total_curency = next_3_char;
total = last_digits;
我想代表它的一種方法是:
(?P<segment>[A-Z])-(?P<scurr>[A-Z]{3})(?P<subtotal>\d+(?:,\d{1,2})?)_(?<desc>^\s*[a-zA-Z,\s]+\s*$)_(?P<curr>[A-Z]{3})(?P<total>\d+(?:,\d{1,2})?)
預期結果將是:
segment = "C";
subtotal_currency = "USD";
subtotal = 10.00;
description = "FRIES AND BURGUER";
total_curency = "USD";
total = 15.00;
如何使用Java中的正則表達式以這種方式分割字符串?
順便說一句,我必須為多種類型的字符串完成這項工作……所以我想使用正則表達式將對我有很大幫助。
正則表達式位於java.util.regex包中。
看來您有正確的主意。 根據Pattern和Matcher類的文檔 ,您唯一需要從模式中刪除的內容是?之間的P。 和<對於命名組,如下所示:
(?<segment>[AZ])-(?<scurr>[AZ]{3})(?<subtotal>\\d+(?:,\\d{1,2})?)_(?<desc>^\\s*[a-zA-Z,\\s]+\\s*$)_(?<curr>[AZ]{3})(?<total>\\d+(?:,\\d{1,2})?)
創建您的Pattern對象,然后在String上調用.matcher()以獲取Matcher。 然后,您可以使用.group(String)方法從Matcher中提取信息。
您可以輕松地使系統通用,但對您的域有所幫助。
(?P<segment>[A-Z])-(?P<scurr>[A-Z]{3})(?P<subtotal>\d+(?:[.,]\d{1,2})?)_(?<desc>\s*[a-zA-Z,\s]+\s*)_(?P<curr>[A-Z]{3})(?P<total>\d+(?:[.,]\d{1,2})?)
^^ ^^
試試看。看演示。
https://regex101.com/r/fX3mH8/2
問題:
1)補充.
隨着,
。
2)從中間字符串中刪除了^$
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.