Tom Rodd
Tom Rodd

Reputation: 53

Regex before a colon

I have this string:

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

I want to grab just the X12 part.

I tried:

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

However, this only gets WALES.

I also tried:

^[^:]+:\s?

But this gets the whole string before and including the colon.

Where am I going wrong?

Upvotes: 0

Views: 1209

Answers (3)

Pshemo
Pshemo

Reputation: 124215

If you wan't to find word (\\w+) between &[ and : then you can use look-around mechanisms

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

Upvotes: 1

bambata
bambata

Reputation: 313

I would use the following regexp \.&\[(.): .] and retrieve the group number 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");

Upvotes: 0

fge
fge

Reputation: 121692

Just try this:

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

&      # 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 ]

In a Java string:

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

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

Upvotes: 0

Related Questions