【问题标题】:exclude a folder and match all .html pattern files in a root folder using regex使用正则表达式排除文件夹并匹配根文件夹中的所有 .html 模式文件
【发布时间】:2023-07-19 03:23:01
【问题描述】:

我正在从 html 迁移到 Drupal。使用迁移模块。

在我们的自定义迁移脚本中,我需要匹配除 images 文件夹之外的所有文件夹中的所有 .html 文件。

将此正则表达式传递给$list_files = new MigrateListFiles([],[],$regex)

下面是html文件的格式

/magazines/sample.html 
/test/index.html
/test/format_ss1.html
/test/folder/newstyle_1.html
/images/two.html

我只需要获取前 2 个 html 文件,即,我们排除了以 '_[0-9]' 和 '_ss[0-9]' 结尾的文件以及 images 文件夹中的 .hmtl 文件。

我已经成功排除了 3 和 4,但我无法排除 images 文件夹中的 .html 文件。

$regex = '/[a-zA-Z0-9\-][^_ss\d][^_\d]+\.html/'; //this will do for 3 and 4 files 

但我需要排除图像文件夹..

我试过了

$regex = '/[^images\/][a-zA-Z0-9\-][^_ss\d][^_\d]+\.html/'; // not working

它在 PHP 脚本中的工作位置

$regex = '~^(?!/images/)[a-zA-Z0-9/-]+(?!_ss\d|\d)\.html$~' //works in php script

有人可以帮我解决这个问题吗..

【问题讨论】:

标签: regex drupal migration


【解决方案1】:

试试 /((?!images)[0-9a-zA-Z])+/[^_]*[^\d]+\.html

匹配:

/magazines/sample.html 
/test/index.html
/test/folder/newstyle.html
/test/format_ss.html

不匹配:

/test/format_ss1.html
/test/folder/newstyle_1.html
/images/two.html
/images/1.html
/test/folder/newstyle1.html
/test/folder/newstyle_12.html

这可以接受吗?

【讨论】:

  • 您可以在online Regex Checker 上验证它,您知道它为什么不工作或哪里出错了吗?
  • @kjhhf:我没有具体原因。但是 ~^(?!/images/)[a-zA-Z0-9/-]+(?!_ss\d|\d)\.html$~.. 这在 php 脚本中会很好用.. 但是它在 Drupal 中不起作用
【解决方案2】:

这是 Drupal/Migrate 特有的问题 - 正则表达式只是文件名(而不是目录)的正则表达式,因为它最终会传递给 https://api.drupal.org/api/drupal/includes%21file.inc/function/file_scan_directory/7

file_scan_directory($dir, $mask, $options = array(), $depth = 0)

$mask:要查找的文件的 preg_match() 正则表达式。

我认为排除某些目录的唯一方法是如果该行具有您不需要的路径,则在 prepareRow() 函数中抛出一个 false。

函数prepareRow($row) prepareRow() 方法由源类 next() 方法在加载数据行后调用。参数 $row 是包含源提供的原始数据的 stdClass 对象。实现 prepareRow() 有两个主要原因:

在数据行通过任何其他方法和处理程序之前对其进行修改:例如,获取相关数据、拆分源字段、基于某些逻辑组合或创建新的源字段。

有条件地跳过一行(通过返回 FALSE)。

https://www.drupal.org/node/1132582

【讨论】:

  • 您能从链接中添加一些内容吗?
  • 内容添加和更完整的答案