57 lines
938 B
Java
57 lines
938 B
Java
# 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+)?");
|
||
}
|
||
```
|
||
|
||
|
||
|
||
|
||
|
||
|
||
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-1.png"></img></div>
|