正则表达式为2个不同的字符串占可选元素

时间:2013-04-07 23:58:48

标签: java regex

我有两个字符串" 2007 AL PLAIN TEXT 5567(NS)"和" 5567"在第二个字符串中,我只想从两个字符串中提取一个组,即5567.如何为此编写java正则表达式?格式将是4位数年份,2位数管辖区域,字符串纯文本,然后是我想提取的数字,最后(NS)但问题是除了数字可以是可选的,我如何为此写一个正则表达式只能在一组中捕获5567号?

2 个答案:

答案 0 :(得分:1)

您可以在一行中完成:

String num = input.replaceAll("(.*?)?(\\b\\w{4,}\\b)(\\s*\\(NS\\))?$", "$2");

假设您的目标是“一个字长至少4个字母数字字符”。

答案 1 :(得分:0)

你需要用吗?量词,这意味着匹配是可选的,'?:'对匹配进行分组,但不为该组创建反向引用。这是代码:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Regexp
{
    public static void main(String args[])
    {
    String x = "2007 AL PLAIN TEXT 5567 (NS)";
    String y = "5567";
    Pattern pattern = Pattern.compile( "(?:.*[^\\d])?(\\d{4,}){1}(?:.*)?");
    Matcher matcher = pattern.matcher(x);

    while (matcher.find()) 
        {
        System.out.format("Text found in x: => \"%s\"\n",
                  matcher.group(1));
        }

    matcher = pattern.matcher(y);

    while (matcher.find()) 
        {
        System.out.format("Text found in y: => \"%s\"\n",
                  matcher.group(1));
        }
    }
}

输出:

$ java Regexp
Text found in x: => "5567"
Text found in y: => "5567"