簡體   English   中英

正則表達式排除以偶數位數結尾的零

[英]Regex to exclude trailing zero with even numbers of digits

我需要一些我要編寫的正則表達式的支持。

我收到了一個始終由8位數字組成的字符串(例如12345678)。 從該字符串中,我需要刪除結尾的零,但始終保持偶數個數字。

因此,例如:

  • 12345678-> 12345678
  • 12345600-> 123456
  • 12345000-> 123450
  • 12003000-> 120030

對我而言,最重要的部分是確保保持偶數。

我嘗試使用一些(\\d\\d)+[^(00)]+但無法實現我想要的功能。

像這樣的簡單正則表達式應該起作用:

(?:00)+$

用空字符串替換。

我使用了一個非捕獲組而不是字符類來將2個零組合在一起,然后添加了一個+量詞以僅匹配2個零的“倍數”,即偶數個零。

演示版

如果您想要一個可以匹配而不是替換的正則表達式,則可以這樣做:

^\d+?0?(?=(?:00)*$)

懶惰地尋找數字,直到達到0。我們是否將此數字匹配為零? 這取決於我們是否在其后看到偶數0。 但是,這不適用於全0的情況,例如0000 ,但是由於您說過永遠不會遇到此值,因此您不必擔心太多。

演示版

試試這個正則表達式:

(?:00)*$

將每個匹配項替換為空白字符串。

點擊演示

說明:

  • (?:00)* -匹配0次或多次出現00
  • $ -聲明行的結尾。
import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "(00)*$";
final String string = "12345678\n"
     + "12400000\n"
     + "12005600\n"
     + "12340000\n"
     + "12000000\n"
     + "12340000\n"
     + "12345000";
final String subst = "";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println("Substitution result: " + result);

以下是結果

Substitution result: 12345678
1240
120056
1234
12
1234
123450

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM