簡體   English   中英

Java字符串的數字部分的正則表達式

[英]Regex for numeric portion of Java string

我正在嘗試編寫一個Java方法,該方法將字符串作為參數,並在匹配模式時返回另一個字符串,否則返回null 模式:

  • 以數字(1個以上的數字)開頭; 然后是
  • 冒號(“ : ”); 然后是
  • 單個空格(“”); 然后是
  • 任何包含1個以上字符的Java字符串

因此,一些與該模式匹配的有效字符串:

50: hello
1: d
10938484: 394958558

還有一些與該模式匹配的字符串:

korfed49
: e4949
6
6:
6:sdjjd4

該方法的一般框架是這樣的:

public String extractNumber(String toMatch) {
    // If toMatch matches the pattern, extract the first number
    // (everything prior to the colon).

    // Else, return null.
}

到目前為止,這是我最好的嘗試,但是我知道我錯了:

public String extractNumber(String toMatch) {
    // If toMatch matches the pattern, extract the first number
    // (everything prior to the colon).
    String regex = "???";
    if(toMatch.matches(regex))
        return toMatch.substring(0, toMatch.indexOf(":"));

    // Else, return null.
    return null;
}

提前致謝。

您的描述很詳細,現在只需將其翻譯為正則表達式即可:

^      # Starts
\d+    # with a number (1+ digits); then followed by
:      # A colon (":"); then followed by
       # A single whitespace (" "); then followed by
\w+    # Any word character, one one more times
$      # (followed by the end of input)

用Java字符串給出:

"^\\d+: \\w+$"

您還想捕獲數字:在\\d+加上括號,使用Matcher ,並在存在匹配項的情況下捕獲組1:

private static final Pattern PATTERN = Pattern.compile("^(\\d+): \\w+$");

// ...

public String extractNumber(String toMatch) {
    Matcher m = PATTERN.matcher(toMatch);
    return m.find() ? m.group(1) : null;
}

注意:在Java中, \\w僅匹配ASCII字符和數字(例如,.NET語言不是這種情況),並且還將匹配下划線。 如果您不想使用下划線,則可以使用(特定於Java的語法):

[\w&&[^_]]

而不是\\w作為正則表達式的最后一部分,給出:

"^(\\d+): [\\w&&[^_]]+$"

嘗試使用以下命令:\\ d +:\\ w +

暫無
暫無

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

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