pistacchio
pistacchio

Reputation: 58953

Non greedy LookAhead

I have strings like follows:

val:key

I can capture 'val' with /^\w*/.

How can I now get 'key' without the ':' sign?

Thanks

Upvotes: 2

Views: 2598

Answers (4)

Paul Dixon
Paul Dixon

Reputation: 301105

How about this?

/^(\w+):(\w+)$/

Or if you just want to capture everything after the colon:

/:(.+)/

Here's a less clear example using a lookbehind assertion to ensure a colon occurred before the match - the entire match will not include that colon.

/(?<=:).*/

Upvotes: 4

Reuben Peeris
Reuben Peeris

Reputation: 541

This will capture the key in group 1 and the value in group 2. It should work correctly even when the value contails a colon (:) character.

^(\w+?):(.*)

Upvotes: 1

Adrian Pronk
Adrian Pronk

Reputation: 13926

What language are you using? /:(.*)/ doesn't capture the ":" but it does match the ':'

In Perl, if you say:

$text =~ /\:(.*)/;
$capture = $1;
$match = $&;

Then $capture won't have the ":" and $match will. (But try to avoid using $& as it slows down Perl: this was just to illustrate the match).

Upvotes: 1

AutomatedTester
AutomatedTester

Reputation: 22438

/\:(\w*)/ 

That looks for : and then captures all the word characters after it till the end of the string

Upvotes: 0

Related Questions