繁体   English   中英

Java Regex 从字符串中提取数字和字符串

[英]Java Regex to extract numbers and strings from a string

我想从字符串中提取数字和字符串。

前任。

“TU111 1998 夏季”

“TU-232 SU 1999”

“TU232 1999 夏季”

我能够使用两种模式来获得它Pattern.compile("\\\\d+")Pattern.compile("[a-zA-Z]+")有没有办法使用一种模式来获得它?

预期的结果应该是

1=>TU 2=> 111/232 3=>1998/1999 4=>夏季/苏

你可以两个正则表达式一起:

[0-9]+|[a-zA-Z]+

演示

试试这个。

Pattern pattern = Pattern.compile("((\\d+)|([a-zA-Z]+))");
        Matcher matcher = pattern.matcher("TU111 1998 SUMMER");
        while (matcher.find()) {
            System.out.println(matcher.group());
        }

嘿,你必须使用 2 个正则表达式 [a-zA-Z]+|[0-9]+ ,也许我下面写的不同代码可能会给你一个提示。只需更新 Pattern.compile() 和 string 就足够了。

Pattern p = Pattern.compile("-?\\d+(,\\d+)*?\\.?\\d+?");
    List<String> numbers = new ArrayList<String>();
    Matcher m = p.matcher("your string");
    while (m.find()) {  
        numbers.add(m.group());
    }   
    System.out.println(numbers);

暂无
暂无

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

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