关于正则表达式的Ansible中的奇怪错误

时间:2017-04-25 12:23:58

标签: regex ansible yaml

replace:
    path: "{{ drupal.install_dir }}/{{ drupal.project_name }}/sites/default/settings.php"
    regexp: '(\s+)(\'database\' => \'{{ drupal.database_name }}\',)$'
    replace: '\1\2\n\1\'charset\' => \'utf8mb4\',\n\1\'collation\' => \'utf8mb4_unicode_ci\','

但是给出错误:

path: "{{ drupal.install_dir }}/{{ drupal.project_name }}/sites/default/settings.php"
regexp: '(\s+)(\'database\' => \'{{ drupal.database_name }}\',)$'
                 ^ here

但它适用于https://regex101.com/

3 个答案:

答案 0 :(得分:1)

使用双引号(然后需要重复反斜杠):

replace:
    path: "{{ drupal.install_dir }}/{{ drupal.project_name }}/sites/default/settings.php"
    regexp: "(\\s+)('database' => '{{ drupal.database_name }}',)$"
    replace: "\\1\\2\\n\\1'charset' => 'utf8mb4',\\n\\1'collation' => 'utf8mb4_unicode_ci',"

答案 1 :(得分:0)

我找到了解决方法:

replace:
        path: "{{ drupal.install_dir }}/{{ drupal.project_name }}/sites/default/settings.php"
        regexp: '^(\s+)(\x27database\x27 => \x27{{ drupal.database_name }}\x27,)$'
        replace: '\1\2\n\1"charset" => "utf8mb4",\n\1"collation" => "utf8mb4_general_ci",'

幸运的是,我可以交换双引号和单引号(PHP数组)。 \ x27解决方法在替换中不起作用,但它在正则表达式中起作用。 (\ x27 =')

答案 2 :(得分:0)

single quote style scalar内,您必须使用额外的单引号“转义”属于该标量的任何单引号:

   regexp: '(\s+)(\''database\'' => \''{{ drupal.database_name }}\'',)$'
   replace: '\1\2\n\1\''charset\'' => \''utf8mb4\'',\n\1\''collation\'' => \''utf8mb4_unicode_ci\'','

在这些单引号样式标量中,不需要(或可以)转义其他字符。