【发布时间】:2019-10-10 05:01:32
【问题描述】:
我有这个字符串:
String filename = 20190516.BBARC.GLIND.statistics.xml;
如何在不使用子字符串的情况下获取字符串的第一部分(数字)。
【问题讨论】:
标签: java regex string regex-group regex-greedy
我有这个字符串:
String filename = 20190516.BBARC.GLIND.statistics.xml;
如何在不使用子字符串的情况下获取字符串的第一部分(数字)。
【问题讨论】:
标签: java regex string regex-group regex-greedy
在这里,我们可能只想使用捕获组来收集我们的数字,如果我们愿意,我们可以稍后添加更多边界,可能使用如下简单的表达式:
([0-9]+)
例如,如果我们想要的数字位于输入的开头,我们可能想要添加一个起始字符作为左边界:
^([0-9]+)
或者如果我们的数字后面总是跟.,我们可以用它来绑定:
^([0-9]+)\.
如果有必要,我们还可以在其后添加一个大写字母来加强我们的右边界并继续这个过程:
^([0-9]+)\.[A-Z]
如果不需要此表达式,可以在 regex101.com 中修改或更改。
jex.im 可视化正则表达式:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "([0-9]+)";
final String string = "20190516.BBARC.GLIND.statistics.xml";
final String subst = "\\1";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
const regex = /([0-9]+)(.*)/gm;
const str = `20190516.BBARC.GLIND.statistics.xml`;
const subst = `$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
【讨论】:
要使用正则表达式提取字符串的一部分或部分,我更喜欢定义组。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class B {
public static void main(String[] args) {
String in="20190516.BBARC.GLIND.statistics.xml";
Pattern p=Pattern.compile("(\\w+).*");
Matcher m=p.matcher(in);
if(m.matches())
System.out.println(m.group(1));
else
System.out.println("no match");
}
}
【讨论】: