冒号前的正则表达式

时间:2013-07-09 11:05:00

标签: java regex

我有这个字符串:

[Provider].[Provider]=[ProviderArea].&[X12: WALES]

我想抓住X12部分。

我试过了:

(?<=: )\w+(?=\]$)

但是,这只会获得WALES

我也尝试过:

^[^:]+:\s?

但是这会在结束之前得到整个字符串。

我哪里错了?

3 个答案:

答案 0 :(得分:1)

如果您不想在\\w+&[之间找到字词:,那么您可以使用look-around机制

(?<=&\\[)\\w+(?=:)

答案 1 :(得分:0)

试试这个:

&\[([^:]+): [^]]+\]

&      # a literal &, followed by
\[     # a literal [, followed by
(      # begin capture
[^:]+  # one or more characters which are not a colon
)      # end capture, followed by
:      # a colon and a space (not shown), followed by
[^]]+  # one or more characters which are not a closing bracket, followed by
\]     # a literal ]

在Java字符串中:

final Pattern p = Pattern.compile("&\\[([^:]+): [^]]+\\]");
final Matcher m = p.matcher(input);

if (m.find())
    // result is in m.group(1)

答案 2 :(得分:0)

我会使用以下regexp \。&amp; \ [(。):。]并检索组号1。

        Pattern pattern = Pattern.compile("\\.&\\[(.*): .*]");

        Matcher matcher = pattern.matcher("[Provider].[Provider]=[ProviderArea].&[X12: WALES]");

        String result = null;

        if(matcher.find())
            result = matcher.group(1);

        if("X12".equals(result))
            System.out.print("Good expression");
        else
        System.out.print("not good");