在字符串中找出连续最长的数字串(含“±”号)
输入描述
输入描述
输出描述
用例
解析
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test2 {
public static void main(String[] args) {
String input = "1234567890abcd9.+12345.678.999999ed-205";
String regex = "([+-]{0,1}\\d+\\.{0,1}\\d+)";// ()括号是匹配表达式 []匹配之内的一个即可
String res = calcResult(regex, input, true);
String reverseRes = calcResult(regex, new StringBuilder(input).reverse().toString(), false);
reverseRes = new StringBuilder(reverseRes).reverse().toString();
// System.out.println(res);
// System.out.println(reverseRes);
if (input.indexOf(res) > input.indexOf(reverseRes)) {
System.out.println(res);
} else {
System.out.println(reverseRes);
}
}
/**
*
* @param regex 匹配模式
* @param input 匹配字符
* @param flag true 正向 false 反向
* @return
*/
public static String calcResult(String regex, String input, boolean flag) {
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(input);
String res = "";
while (matcher.find()) {
if (flag && matcher.group().length() >= res.length()) {
res = matcher.group(); // 正向取后
} else if ((!flag) && matcher.group().length() > res.length()) {
res = matcher.group(); // 反向取前
}
}
return res;
}
}
代码运行示意图