Home > Net >  if else in regex?
if else in regex?

Time:10-27

My import file contains a column params. This column can contain a string of parameters separated by |, for example name:value|name1:value1|name2:value2. But sometimes this column may contain other parameters, for example other_name|other_value.

I need a regular expression that would remove everything from this column except value2. And if the column does not find value2 at all, then return an empty row.

I'm trying something like this (?(?=.*).*name2:), but it doesn't work if the row contains other data that needs to be deleted completely.

CodePudding user response:

You can use

preg_match('~\bname2:([^|]*)~', $text, $m)

See the regex demo. Details

  • \bname2 - a whole word name2
  • : - a colon
  • ([^|]*) - Group 1: any zero or more chars other than |.

See the PHP demo:

$text = "name:value|name1:value1|name2:value2";
$result = "";
if (preg_match('~\bname2:([^|]*)~', $text, $m)) {
    $result = $m[1];
}
echo $result;
// => value2

CodePudding user response:

You can either capture the part after name2: and use group 1 in the replacement, and if it is not there match the whole string to be removed.

.*\bname2:([^|\n] ).*|. 
  • .*\bname2: Match till name2:
  • ([^|\n] ) Capture group 1, match 1 or more following chars other than | as that is the delimiter
  • .* Optionally match the rest of the line
  • | Or
  • . Match 1 or more characters

Regex demo | Php demo

$re = '/.*\bname2:([^|\n] ).*|. /';
$str = 'name:value|name1:value1|name2:value2
name:value|name1:value1|name2:value2|name:value
other_name|other_value';

$result = preg_replace($re, '$1', $str);

echo $result;

Output

value2
value2
  • Related