[英]Java Regex pattern to match String from all languages that end with a whitespace
[英]How to build a Regex in java to detect a whitespace or end of a string?
我試圖建立一個正則表達式來查找和提取包含郵政信箱的字符串。 這是兩個示例:
這是我的模式和代碼:
Pattern p = Pattern.compile("p.*o.*box \\d+(\\z|\\s)");
Matcher m = p.matcher(str);
int count =0;
while(m.find()) {
count++;
System.out.println("Match number "+count);
System.out.println("start(): "+m.start());
System.out.println("end(): "+m.end());
}
它與第二個示例配合使用,並為第一個示例提供注釋! 如果將我的模式更改為以下內容:
模式p = Pattern.compile(“ p。* o。* box \\ d +”);
它僅適用於第一個示例。 問題是如何將正則表達式分組為字符串“ \\ z”的末尾,將正則表達式分組為空格“ \\ s”或“”?
新模式:模式p = Pattern.compile(“(?i)((p。* o。box \\ s \\ w \\ s * \\ d *(\\ z | \\ s *)|(box \\ s * \\ w \\ s * \\ d *(\\ z | \\ s *))))“);
正則表達式中有幾項看起來需要工作。 據我了解,您想從您提供的這種格式的字符串中提取郵政信箱號碼。 鑒於此,以下正則表達式將完成您所需的內容,並提供以下說明。 在此處查看其運行情況: https : //regex101.com/r/cQ8lH3/2
Pattern p = Pattern.compile("p\\.?o\\.? box [^ \\r\\n\\t]+");
首先,對於轉義序列,您只需使用一個斜杠。 另外,您必須避開這些點。 如果您不逃避這些點,則正則表達式將匹配.
作為任何單個字符。 \\.
而是匹配點符號。
接下來,您需要在\\.
后面更改*
量詞 \\.
到一個?
。 為什么? *
符號將匹配零個或多個前面的符號,而?
量詞僅匹配一個或不匹配。
最后重新考慮一下您如何匹配箱號。 與其匹配所有字符,然后匹配空格,不如匹配所有非空格。 [^ \\r\\n\\t]+
將匹配所有非空格字符( ),回車符(
\\r
),換行符( \\n
)或制表符( \\t
)。 因此,它將消耗存儲箱編號並在遇到任何空白或文件結尾時立即停止。
為了使您的代碼適用於您給出的示例,其中的某些更改可能不是必需的,但它們是構建所需正則表達式的正確方法。
您可以利用以下代碼 :
String str = "some text p.o. box 12456 Floor 105 streetName Street";
Pattern p = Pattern.compile("(?i)\\bp\\.?\\s*o\\.?\\s*box\\s*(\\d+)(?:\\z|\\s)");
Matcher m = p.matcher(str);
int count =0;
while(m.find()) {
count++;
System.out.println("Match: "+m.group(0));
System.out.println("Digits: "+m.group(1));
System.out.println("Match number "+count);
System.out.println("start(): "+m.start());
System.out.println("end(): "+m.end());
}
要使模式不區分大小寫,只需將Pattern.CASE_INSENSITIVE
標志添加到Pattern.compile
聲明中,或將內聯(?i)
修飾符添加到模式之前。
另外, .*
匹配除換行符以外的任何其他字符0次或多次,我想您想匹配.
可選。 所以,您只需要?
量詞和轉義點以匹配文字點。 請注意我是如何使用(...)
將數字捕獲到組1中的(稱為捕獲組 )。 與字符串或空格結尾匹配的組位於非捕獲組 ( (?:...)
)內,該組僅用於分組,而不用於將其值存儲在內存緩沖區中。 由於您想在那里匹配單詞邊界,因此我建議僅用\\\\b
代替(?:\\\\z|\\\\s)
:
Pattern p = Pattern.compile("(?i)\\bp\\.?\\s*o\\.?\\s*box\\s*(\\d+)\\b");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.