Re: Help with regular expression



Tony Marston wrote:
> I am seeking help with a regular expression that will split a string into
> several parts with ',' (comma) as the separator, but NOT where the separator
> is enclosed in parentheses. For example, take the string "field1,
> CONCAT(field2,' ', field3) as field23, field4". I would like to be able to
> split this into the following:
> [0] field1
> [1] CONCAT(field2,' ', field3) as field23
> [2] field4

Can it happen that you will have nested parenthesis? :-)
Would you consider dumping preg_* function and parsing the string?

<?php
function parse_split_comma_ignore_paren($text) {
$retval = array();
$paren = 0;
$last_index = 0;
for ($index = 0; $index < strlen($text); ++$index) {
if ($text{$index} == '(') {++$paren; continue;}
/* assumes $paren will never be negative */
if ($text{$index} == ')') {--$paren; continue;}
if ($paren) continue;
if ($text{$index} == ',') {
$retval[] = trim(substr($text, $last_index, $index-$last_index));
$last_index = $index + 1;
}
}
$retval[] = trim(substr($text, $last_index));
return $retval;
}

$s = 'field1, CONCAT(field2, \' \', field3) as field23, field4,1,,3,4';

$parts = parse_split_comma_ignore_paren($s);
print_r($parts);
?>

--
Mail to my "From:" address is readable by all at http://www.dodgeit.com/
== ** ## !! ------------------------------------------------ !! ## ** ==
TEXT-ONLY mail to the whole "Reply-To:" address ("My Name" <my@address>)
may bypass my spam filter. If it does, I may reply from another address!
.



Relevant Pages

  • Regular Expression Help
    ... I need to find all occurrences of a comma in a string EXCEPT where it ... I figured a regular expression would be the way to go, ... of various RegEx test programs, but I would like one to help me construct ...
    (microsoft.public.dotnet.languages.vb)
  • Comma delimited list regular expression correctness proof
    ... only comma separated lists including a null list. ... regular expression accepts all possible strings. ... Any other string either ...
    (comp.programming)
  • Re: while reading mastering perl @+ and @-, not too clear on this
    ... If you want to explore all the gory details of regular expressions then get the book _Mastering Regular Expression_ by Jeffrey E. F. Friedl: ... possible comma) ... I am not totally understanding how the first line is matching standard quoted string. ...
    (perl.beginners)
  • Re: Please help with grep and sed commands
    ... by a comma, ... The input string is "consumed" up to and including the second comma by ... you can apply the same substitution rule twice: ... In perl a regular expression can "look ahead" for an expression ...
    (comp.os.linux.misc)
  • Re: regular expression question
    ... I'd like to use regular expression for checking validity of a field. ... firstname, lastname, organisation23 ... a string + comma then another string + comma then a ...
    (comp.lang.javascript)