## 2. 计算数字

### 2.1.使用正则表达式

``````int countDigits(String stringToSearch) {
Pattern digitRegex = Pattern.compile("\\d");
Matcher countEmailMatcher = digitRegex.matcher(stringToSearch);

int count = 0;
while (countEmailMatcher.find()) {
count++;
}

return count;
}
``````

``````int count = countDigits("64x6xxxxx453xxxxx9xx038x68xxxxxx95786xxx7986");

assertThat(count, equalTo(21));
``````

``````<dependency>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
``````

Guava 提供了 CharMatcher.inRange​ 方法 来计算数字：

``````int count = CharMatcher.inRange('0', '9')
.countIn("64x6xxxxx453xxxxx9xx038x68xxxxxx95786xxx7986");

assertThat(count, equalTo(21));
``````

## 3. 寻找数字

### 3.1.寻找整数

``````List<String> findIntegers(String stringToSearch) {
Pattern integerPattern = Pattern.compile("-?\\d+");
Matcher matcher = integerPattern.matcher(stringToSearch);

List<String> integerList = new ArrayList<>();
while (matcher.find()) {
}

return integerList;
}
``````

``````List<String> integersFound =
findIntegers("646xxxx4-53xxx34xxxxxxxxx-35x45x9xx3868xxxxxx-95786xxx79-86");

assertThat(integersFound)
.containsExactly("646", "4", "-53", "34", "-35", "45", "9", "3868", "-95786", "79", "-86");
``````

### 3.2.求小数

``````List<String> findDecimalNums(String stringToSearch) {
Pattern decimalNumPattern = Pattern.compile("-?\\d+(\\.\\d+)?");
Matcher matcher = decimalNumPattern.matcher(stringToSearch);

List<String> decimalNumList = new ArrayList<>();
while (matcher.find()) {
}

return decimalNumList;
}
``````

``````List<String> decimalNumsFound =
findDecimalNums("x7854.455xxxxxxxxxxxx-3x-553.00x53xxxxxxxxxxxxx3456xxxxxxxx3567.4xxxxx");

assertThat(decimalNumsFound)
.containsExactly("7854.455", "-3", "-553.00", "53", "3456", "3567.4");
``````

## 4. 将找到的字符串转换为数值

``````LongStream integerValuesFound = findIntegers("x7854x455xxxxxxxxxxxx-3xxxxxx34x56")
.stream()
.mapToLong(Long::valueOf);

assertThat(integerValuesFound)
.containsExactly(7854L, 455L, -3L, 34L, 56L);
``````

``````DoubleStream decimalNumValuesFound = findDecimalNums("x7854.455xxxxxxxxxxxx-3xxxxxx34.56")
.stream()
.mapToDouble(Double::valueOf);

assertThat(decimalNumValuesFound)
.containsExactly(7854.455, -3.0, 34.56);
``````

## 5. 查找其他类型的数字

### 5.1.科学计数法

``````String strToSearch = "xx1.25E-3xxx2e109xxx-70.96E+105xxxx-8.7312E-102xx919.3822e+31xxx";

Matcher matcher = Pattern.compile("-?\\d+(\\.\\d+)?[eE][+-]?\\d+")
.matcher(strToSearch);

// loop over the matcher

assertThat(sciNotationNums)
.containsExactly("1.25E-3", "2e109", "-70.96E+105", "-8.7312E-102", "919.3822e+31");
``````

### 5.2.十六进制

``````String strToSearch = "xaF851Bxxx-3f6Cxx-2Ad9eExx70ae19xxx";

Matcher matcher = Pattern.compile("-?[0-9a-fA-F]+")
.matcher(strToSearch);

// loop over the matcher

assertThat(hexNums)