簡體   English   中英

如何為字符串編寫正則表達式模式以標識空格或連字符前面的數字?

[英]How do i write regex pattern for a String to identify numbers that precedes space or hypen?

我有一個自由流動的字符串,其中包含一些隨機文本,如下所示:

  • "Some random text 080 2668215901"
  • "Some ramdom text 040-1234567890"
  • "Some random text 0216789101112"

我需要捕獲3位數字和以下10位數字:

  • 有空間條件
  • 處於低潮狀態
  • 沒有任何空間/連字符

我正在使用Java。

這就是我試圖從自由流動的文本中獲取數字的方法:

"\\w+([0-9]+)\\w+([0-9]+)"

我可以進行字符串長度檢查,以查看是否在連字符或空格之前有3位數字,然后是10位數字,但我真的很想探究正則表達式是否可以為我提供更好的解決方案。

另外,如果字符串中有更多的事件,則需要捕獲所有事件。 我還需要捕獲任何10位字符串,而不必在連字符和空格之前

通常是(\\d{3})[ -]?(\\d{10})
具有邊界條件的情況可能是(?<!\\d)(\\d{3})[ -]?(\\d{10})(?!\\d)

假設您將在單獨的行上運行此正則表達式,而忽略了某些...更具表現力的正則表達式實現,這也許是最簡單的方法:

/([0-9]{3})[ -]?([0-9]{10})/

如果您的文本可能以數字結尾,則需要將結果錨定到該行的末尾,如下所示:

/([0-9]{3})[ -]?([0-9]{10})$/

如果可以保證輸入內容的雙引號文字,則可以改用:

/([0-9]{3})[ -]?([0-9]{10})"$/

如果需要對整行進行匹配以進行某些輸入錯誤測試,則可以使用:

/^"(.+)([0-9]{3})[ -]?([0-9]{10})"$/

這是更長的演示。 從上面的回答中,您還需要在比賽后尋找帶有尾部字符的比賽。

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

class Class {
  private static final Pattern p = Pattern.compile("" +
    "((?<threeDigits>\\d{3})[- ]?)?" +
    "(?<tenDigits>\\d{10})");

  public static void main(String... args) {
    final String input =
      "Here is some text to match: Some random text 080 2668215901. " +
        "We're now matching stray sets of ten digit as well: 1234567890. " +
        "Notice how you get the first ten and the second ten, with the preceding three:1234123412-040-1234567890" +
        "A stranger case:111222333444555666777888. Where should matches here begin and end?";
    printAllMatches(p.matcher(input));
  }

  private static void printAllMatches(final Matcher m) {
    while (m.find()) {
      System.out.println("three digits: " + m.group("threeDigits"));
      System.out.println("ten digits: " + m.group("tenDigits"));
    }
  }

}

轉而尋找所有戰斗計划。

暫無
暫無

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

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