0

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.

2
  • which language you using? PHP? C? ObjectiveC? Java? Commented Oct 15, 2011 at 17:08
  • You have to specify the language of the Regexes AND It isn't clear how you would write a third group 2045111780&&-3&5&-7&4&-8? Or it would repeat the double &&? Commented Oct 15, 2011 at 17:12

4 Answers 4

4

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', ...
Sign up to request clarification or add additional context in comments.

1 Comment

i agree. can't do it in regex itself.
0

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

2 Comments

it does not group the delim. i want num1, delim, num2 as groups.
If you want to match the -3 twice, I think you'll have to write some code in addition to the regex.
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.