[英]How to extract a sequence of 7 numbers from a String in Java?
假设我有一些String
object 包含"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)。
为此,您可能需要使用Pattern
API:
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);
}
我刚刚验证了它,它工作正常。
(从这个答案中提取的模式
假设位数并不总是 7,我会使用正则表达式
" ([0-9]+) "
内部[0-9]+
查找一位或多位数字。 它的左右空格确保只有在被空格包围的情况下才能找到数字,因此输入字符串中的日期和时间将被忽略。 括号与group(1)
结合使用,仅返回数字,周围没有空格。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main
{
private static final Pattern regexp=Pattern.compile(" ([0-9]+) ");
public static void main(String[] args)
{
String s="This sentence was written on 2020-03-21 by person 1234567 at 07:23 hours";
Matcher matcher=regexp.matcher(s);
if (matcher.find())
{
String number=matcher.group(1);
System.out.printf("number=%s",number);
}
}
}
要仅查找 5 - 8 位数字,您可以编写" ([0-9]{5,8}) "
正如其他人同时写的那样, \\d
可以用作[0-9]
的替代品。
您可以进行简单的linear search
以找到length
7 的numeric
ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ:
public static void main(String[] args) {
String str = "This sentence was written on 2020-03-21 by person 1234567 at 07:23 hours";
System.out.println(getNumber(str));
}
private static String getNumber(String str) {
String number = null;
if(str != null)
for(String s : str.split(" "))
if(s.length() == 7 && isNumeric(s))
number = s;
return number;
}
private static boolean isNumeric(String str) {
try {
Integer.parseInt(str);
return true;
} catch(NumberFormatException e){
return false;
}
}
Output:
1234567
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.