![](/img/trans.png)
[英]Regex in java to find if a String is in the format of a decimal number with a trailing zero
[英]Regex to find integer or decimal from a string in java in a single group?
我在這個示例字符串上嘗試(\\d+|\\d+\\.\\d+)
:
Oats 124 0.99 V 1.65
但是當我在Java中使用模式匹配器類時,它給出了不同組中的十進制數。
我希望我的答案在一個小組中。
您不需要為整數和浮點數設置單獨的模式。 只需將小數部分設為可選,您就可以從一個組中獲得兩種類型的數字。
(\d+(?:\.\d+)?)
使用上面的模式並從組索引1中獲取數字。
碼:
String s = "Oats 124 0.99 V 1.65";
Pattern regex = Pattern.compile("(\\d+(?:\\.\\d+)?)");
Matcher matcher = regex.matcher(s);
while(matcher.find()){
System.out.println(matcher.group(1));
}
輸出:
124
0.99
1.65
模式說明:
要么
只有在更改模式的順序時,正則表達式才會起作用。
(\d+\.\d+|\d+)
試試這種模式:
\d+(?:\.\d+)?
Edit:
\d+ match 1 or more digit
(?: non capturing group (optional)
\. '.' character
\d+ 1 or more digit
)? Close non capturing group
問題不完全清楚,但我看到的第一個問題是。 是正則表達式中的魔法角色,意為任何角色。 你需要用as來逃避它。 那里有很多正則表達式的備忘單,例如JavaScript Regex Cheatsheet
(\d+|\d+\.\d+)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.