hIpPy
hIpPy

Reputation: 5125

regex expression help for string

I have a string

2045111780&&-3&5&-7

I want a regex to give me groups as:

2045111780
&&-
3

... and then next groups as

3
&
5

... and so on.

I came up with (\d+)(&&?-?)? but that gives me groups as:

2045111780
&&-

... and then next groups as

3
&

... and so on.

Note that I need the delim ( regex: &&?-? )

Thanks.

update1: changed the groups output.

Upvotes: 0

Views: 51

Answers (4)

Mat
Mat

Reputation: 206859

You could do it in perl like this:

$ perl -ne 'while (/(-?\d+)(&&?)(-?\d+)/g) { print $1, " ", $2, " ", $3, "\n"; pos() -= length($3); }'
2045111780&&-3&5&-7  # this is the input
2045111780 && -3
-3 & 5
5 & -7

But that's very ugly. The split approach by Miguel Prz is much, much cleaner.

Upvotes: 0

Miguel Prz
Miguel Prz

Reputation: 13792

I think it's not possible to share a match between groups (the -3 in your example). So, I recommend to do a 2 line processing: split the spring and take 2 pairs in an array. For example, using Perl:

$a = "2045111780&&-3&5&-7";
@pairs = split /&+/, $a;
# at this point you get $pairs[0] = '2045111780', $pairs[1] = '-3', ...

Upvotes: 4

rczajka
rczajka

Reputation: 1840

If I understand correctly, you want to have overlapping matches.

You could use a regex like (-?\d+)(&&?)(-?\d+) and match it repeatedly until it fails, each time removing the beginning of the given string up to the start of the third group.

Upvotes: 0

Tetaxa
Tetaxa

Reputation: 4403

How about (-?\d+|&+). It will match numbers with an optional minus and sequences of &s.

Upvotes: 0

Related Questions