簡體   English   中英

唯一整數字符串的Java正則表達式是什么?

[英]What's the Java regular expression for an only integer numbers string?

我正在嘗試if (nuevo_precio.getText().matches("/^\\\\d+$/"))但到目前為止得不到好結果......

在Java正則表達式中,您不使用分隔符/

nuevo_precio.getText().matches("^\\d+$")

由於String.matches() (或Matcher.matcher() )強制整個字符串與模式匹配以返回true ,因此^$實際上是多余的,可以在不影響結果的情況下刪除。 與JavaScript,PHP(PCRE)或Perl相比,這有點不同,其中“匹配”意味着在目標字符串中查找與模式匹配的子字符串。

nuevo_precio.getText().matches("\\d+") // Equivalent solution

但是,將它留在那里並沒有什么壞處,因為它表示意圖並使正則表達式更具可移植性。


要限制正好是 4位數:

"\\d{4}"

正如其他人已經說過的那樣,java不使用分隔符。 你想要匹配的字符串不需要尾部斜杠,所以代替/^\\\\d+$/你的字符串應該是^\\\\d+$

現在我知道這是一個古老的問題,但這里的大多數人都忘記了非常重要的事情。 正確的整數正則表達式:

^-?\d+$

打破它:

^         String start metacharacter (Not required if using matches() - read below)
 -?       Matches the minus character (Optional)
   \d+   Matches 1 or more digit characters
       $  String end metacharacter (Not required if using matches() - read below)

當然,在Java中你需要一個雙反斜杠而不是常規的反斜杠,所以匹配上述正則表達式的Java字符串是^-?\\\\d+$


注意:如果您使用.matches() ,則不需要^$ (字符串開頭/結尾)字符:

歡迎使用Java的錯誤名稱.matches()方法...它嘗試並匹配所有輸入。 不幸的是,其他語言也紛紛效仿:(

- 取自這個答案

正則表達式仍然適用於^$ 即使它是可選的,我仍然將它包含在正則表達式可讀性中,就像在其他情況下默認情況下你不匹配整個字符串一樣(大多數情況下,如果你不使用.matches() ) d使用這些字符


相反的情況:

^\D+$

\\D是不是數字的一切。 \\D (非數字)否定\\d (數字)。

regex101上的整數正則表達式


請注意,這僅適用於整數 雙打的正則表達式:

^-?\d+(\.\d+)?$

打破它:

^         String start metacharacter (Not required if using matches())
 -?               Matches the minus character. The ? sign makes the minus character optional.
   \d+           Matches 1 or more digit characters
       (          Start capturing group
        \.\d+     A literal dot followed by one or more digits
             )?   End capturing group. The ? sign makes the whole group optional.
               $  String end metacharacter (Not required if using matches())

當然用Java代替\\d\\. 你有雙反斜杠,如上例所示。

regex101上的雙重正則表達式

Java不使用斜杠來分隔正則表達式。

.matches("\\d+")

應該這樣做。

FYI String.matches()方法必須匹配整個輸入才能返回true


即使在像perl這樣的語言中,斜杠也不是正則表達式的一部分; 它們是分隔符 - 如果是應用程序代碼,則與正則表達式無關

你也可以去否定來檢查數字是否是純數字。

Pattern pattern = Pattern.compile(".*[^0-9].*");
for(String input: inputs){
           System.out.println( "Is " + input + " a number : "
                                + !pattern.matcher(input).matches());
}
    public static void main(String[] args) {
    //regex is made to allow all the characters like a,b,...z,A,B,.....Z and 
    //also numbers from 0-9.
    String regex = "[a-zA-z0-9]*";

    String stringName="paul123";
    //pattern compiled   
    Pattern pattern = Pattern.compile(regex);

    String s = stringName.trim();

    Matcher matcher = pattern.matcher(s);

    System.out.println(matcher.matches());
    }

正則表達式適用於數字,而不是整數:

Integer.MAX_VALUE

暫無
暫無

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

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