tags:

views:

248

answers:

2

Hi all,

I have three variations of a string:

1. view=(edit:29,30)
2. view=(edit:29,30;)
3. view=(edit:29,30;x:100;y:200)

I need a RegExp that:

  1. capture up to and including ",30"
  2. capture "x:100;y:200" - whenever there's a semicolon after the first match;
  3. WILL NOT include leftmost semicolon in any of the groups;
  4. entire string on the right of the first semicolon and up to ')' can/should be in the same group.

I came up with:

$pat = '/view=\((\w+)(:)([\d,]+)((;[^)]+){0,}|;)\)/';

Applied to 'view=(edit:29,30;x:100;y:200)' it yields:

Array
(
    [0] => view=(edit:29,30;x:100;y:200)
    [1] => edit
    [2] => :
    [3] => 29,30
    [4] => ;x:100;y:200
    [5] => ;x:100;y:200
)

THE QUESTION. How do I remove ';' from matches [4] and [5]?

IMPORTANT. The same RegExp should work with a string when no semicolons are present, as: 'view=(edit:29,30)'.

$pat = '/view=\((\w+)(:)([\d,]+)((;[^)]+){0,}|;)\)/';
$str = 'view=(edit:29,30;x:100;y:200)';
preg_match($pat, $str, $m);
print_r($m);

Thanks!

+3  A: 

You don’t need to group everything. Try this regular expression:

/view=\((\w+):([\d,]+)(?:;([^)]+)?)?\)/
Gumbo
A: 

I guess you want something like this:

$pattern = '/view=\\((\\w+):(\\d+,\\d+)(?:;((?:\\w+:\\d+;?)*))?\\)/';

Should return

[0] view=(edit:29,30;x:100;y:200)
[1] edit
[2] 29,30
[3] x:100;y:200
Blixt