CS-Notes/notes/20. 表示数值的字符串.md
2020-11-17 00:32:18 +08:00

50 lines
782 B
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 20. 表示数值的字符串
[NowCoder](https://www.nowcoder.com/practice/6f8c901d091949a5837e24bb82a731f2?tpId=13&tqId=11206&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 题目描述
```
true
"+100"
"5e2"
"-123"
"3.1416"
"-1E-16"
```
```
false
"12e"
"1a3.14"
"1.2.3"
"+-5"
"12e+4.3"
```
## 解题思路
使用正则表达式进行匹配
```html
[] 字符集合
() 分组
? 重复 0 ~ 1
+ 重复 1 ~ n
* 重复 0 ~ n
. 任意字符
\\. 转义后的 .
\\d 数字
```
```java
public boolean isNumeric(char[] str) {
if (str == null || str.length == 0)
return false;
return new String(str).matches("[+-]?\\d*(\\.\\d+)?([eE][+-]?\\d+)?");
}
```