如何写正则表达式从Java字符串提取数字?



例如,我有一组文字"1234568asdjhgsd",我只想得到数字,我该怎么办?下面是我的代码,他不能执行到while步骤

textView.setText("1234568asdjhgsd");
String str = (String) textView.getText();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Pattern p;
p = Pattern.compile("\d{10}");
Matcher m;
m = p.matcher(str);

while (m.find()){
String xxx = m.group();
System.out.println(xxx);
}
}
});

它没有打印任何东西

p = Pattern.compile("\d{10}");匹配10位数字,但您的文本"1234568asdjhgsd"只有7个数字。你可以用Pattern.compile("\d{7}");,也可以。但位数必须总是<= 7。

如果匹配数字则打印出来。

String str = "1234568asdjhgsd"; 
Pattern p;
p = Pattern.compile("\d");
Matcher m;
m = p.matcher(str);

while (m.find()){
String xxx = m.group();
System.out.print(xxx);
}

您可以使用java方法replaceAll与regex。它看起来像这样:

String someString = "1234568asdjhgsd";
String replacedString = someString.replaceAll("0-9","");

replaceAll的第一个参数表示它只接受0到9之间的数字,第二个参数表示要改变的内容

最新更新