Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/429.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从正则表达式和结果构造字符串(反向匹配)_Javascript_Php_Python_Regex_Preg Match - Fatal编程技术网

Javascript 从正则表达式和结果构造字符串(反向匹配)

Javascript 从正则表达式和结果构造字符串(反向匹配),javascript,php,python,regex,preg-match,Javascript,Php,Python,Regex,Preg Match,有没有可靠的方法从给定的正则表达式和“匹配”结果构造字符串 我正在寻找类似于: stringConstruct('/My name is (?P<name>.*)/', {name: John}); stringConstruct('/My name is(?P.*)/',{name:John}); 结果是“我的名字叫约翰”。所以我需要反向函数来匹配regexp 用任何非异或语言回答都是合适的。简短的回答是“不”——这不是正则表达式的用途 但是,你可以这样做: function

有没有可靠的方法从给定的正则表达式和“匹配”结果构造字符串

我正在寻找类似于:

stringConstruct('/My name is (?P<name>.*)/', {name: John});
stringConstruct('/My name is(?P.*)/',{name:John});
结果是“我的名字叫约翰”。所以我需要反向函数来匹配regexp

用任何非异或语言回答都是合适的。

简短的回答是“不”——这不是正则表达式的用途

但是,你可以这样做:

function stringConstruct($stringTemplate, $regex, $input){

     if(preg_match($regex, $input)){
        return  str_replace($regex, $input, $stringTemplate);    
      } else { 
         return false;
      }
}
但是,您必须像这样使用它:


echo stringConstruct('我的名字是/(?p.*)/','/(?p.*)/',“约翰”)

您可以编写自己的函数。我用Java做过一次,下面是一个例子。某人是一根需要处理的绳子。replaceMap是(regexp,replaceStr)映射:

publicstaticbooleanplaceall(stringbuffersb,Map replaceMap)
{
布尔值=假;
迭代器it=replaceMap.keySet().Iterator();
while(it.hasNext())
{
String toReplace=it.next();
Matcher mat=Pattern.compile(toReplace).Matcher(sb);
while(mat.find())
{
如果(!更改)
{
改变=正确;
}
String str=(String)replaceMap.get(toReplace);
sb.替换(材料开始(),材料结束(),材料终止);
材料区域(材料起点()+str.length(),sb.length());
}
}
更改退货;
}
总是有感谢,长答案也是“否”,我想我需要“猜测”原始输入字符串,只有regexp和匹配的结果。我不知道正则表达式的结构。这是一个模棱两可的过程。我只能用提供的数据替换顶级命名子节点,忽略了许多正则表达式部分(未命名的通配符)
  public static boolean replaceAll(StringBuffer sb, Map<String,String> replaceMap)
  {
    boolean altered = false;
    Iterator<String> it = replaceMap.keySet().iterator();
    while (it.hasNext())
    {
      String toReplace = it.next();
      Matcher mat = Pattern.compile(toReplace).matcher(sb);
      while (mat.find())
      {
        if (!altered)
        {
          altered = true;
        }
        String str = (String) replaceMap.get(toReplace);
        sb.replace(mat.start(), mat.end(), str);
        mat.region(mat.start() + str.length(), sb.length());
      }
    }

    return altered;
  }