繁体   English   中英

RegEx用于捕获字符串中的数字

[英]RegEx for capturing digits from a string

我有这个字符串:

String filename = 20190516.BBARC.GLIND.statistics.xml;

我如何在不使用子字符串的情况下获取字符串的第一部分(数字)。

在这里,我们可能只想使用捕获组来收集数字,并且,如果我们愿意,我们以后可以添加更多边界,也许使用简单的表达式即可:

([0-9]+)

例如,如果我们想要的数字在输入的开头,我们可能想添加一个起始字符作为左边界:

^([0-9]+)

或者,如果我们的数字后总是跟一个数字. ,我们可以将其与之绑定:

^([0-9]+)\.

如果需要,我们还可以在其后添加一个大写字母以增强我们的右边界并继续此过程:

^([0-9]+)\.[A-Z]

在此处输入图片说明

正则表达式

如果不需要此表达式,则可以在regex101.com中对其进行修改或更改。

RegEx电路

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");
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM