mde*_*nci 2 java string sequence
假设我有一些String包含"This sentence was written on 2020-03-21 by person 1234567 at 07:23 hours". 我如何仅提取"1234567"字符串的一部分?也许使用从字符串中提取数字 - StringUtils Java问题中的解决方案,但我不知道如何仅将提取的数字限制在所需的序列上。
如果我在这个字符串上使用str.replaceAll("[^0-9]", ""),我会得到"2020032112345670723"这意味着它提取字符串中的所有数字,但我只想要包含一定数量数字的序列(在我的例子中是 7)。
此外,序列并不总是在同一位置,因此使用substring(index from, index to)将不起作用。
我可能会使用正则表达式来做到这一点。对于七个相邻的数字,这将是\d{7}甚至更好\b\d{7}\b(感谢@AlexRudenko)。
为此,您可能需要使用PatternAPI:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// ...
Pattern digitPattern = Pattern.compile("\\b\\d{7}\\b");
Matcher m = digitPattern.matcher(<your-string-here>);
while (m.find()) {
String s = m.group();
// prints just your 7 digits
System.out.println(s);
}
Run Code Online (Sandbox Code Playgroud)
我刚刚验证了它并且工作正常。
(模式提取取自这个答案
| 归档时间: |
|
| 查看次数: |
847 次 |
| 最近记录: |