最后一场比赛没有组正则表达式

时间:2018-02-15 09:39:45

标签: javascript regex regex-group

如示例代码 fstr 中所示,需要匹配 regEx_C 的所有出现,并且需要替换为某个动态值。并确保每场比赛都应具有独特的价值。

在此示例 fstr.match(regEX_C)匹配4匹配,我需要替换为每个动态值1。

  1. var_Viablecells_C = X
  2. var_IVCC_C = Y
  3. var_Viablecells_C = Z
  4. var_IVCC_C = Z1

    指定的值不应与任何人匹配。

  5. var fstr = '(Math.log(var_Viablecells_C-var_Viablecells_P)/(2-1)+ var_IVCC_C + var_Viablecells_C / var_IVCC_C)';
    var regEx_C = /var_(\w+)_C/ig;
    var c_val = 5.5;
    
    function putExpValForRegExMatch(fstr, regEx, val) {
      var all_match = fstr.match(regEx);
      if (null == all_match) return fstr;
      console.log(all_match);
      for (var i = 0; i < all_match.length; i++) {
        console.log(i);
        console.log(fstr);
        var current_match = regEx.exec(fstr);
        if (current_match == null) return fstr;
        console.log(current_match);
        fstr = replaceRange(fstr, current_match.index, current_match.index + current_match[0].length - 1, '');
        fstr = replaceAt(fstr, current_match.index, val);
        console.log(fstr);
      }
      return fstr;
    }
    
    function replaceAt(string, index, replace) {
      return string.substring(0, index) + replace + string.substring(index + 1);
    }
    
    function replaceRange(s, start, end, substitute) {
      return s.substring(0, start) + substitute + s.substring(end);
    }
    
    console.log(putExpValForRegExMatch(fstr, regEx_C, c_val));

1 个答案:

答案 0 :(得分:0)

您可以使用var fstr = '(Math.log(var_Viablecells_C-var_Viablecells_P)/(2-1)+ var_IVCC_C + var_Viablecells_C / var_IVCC_C)'; var regEx_C = /var_(\w+)_C/ig; var c_val = 5.5; output = fstr.replace(regEx_C,c_val)

<?php
$GLOBALS['server']="localhost";
$GLOBALS['username']="root";
$GLOBALS['password']="*****";
$GLOBALS['database']="performance";

$GLOBALS['conn']= mysqli_connect($server,$username,$password,$database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";    

$GLOBALS['db'] = mysqli_connect($server,$username,$password,$database);

$sql="INSERT INTO animals (id,name) VALUES('2211','vidya');";
$sql .="INSERT INTO birds (id,fame) VALUES('2211','viddi');";
//mysqli_query($conn,$sql);
//mysqli_query($conn,$sql1);
if (mysqli_multi_query($GLOBALS['db'], $sql)) {
    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>