如何使用正则表达式查找字符串作为 Behat 的通配符?

How to find strings with regex as wildcards with Behat?

我想创建一个允许我查找带有通配符的文本的 Behat 规则,因为我找不到与之相近的任何内容。

我有时需要在 Drupal 项目中创建一些内容,但标题不是由用户定义的,所以我在 运行 测试之前无法知道保存时标题是什么。即,在我的情况下,我想检查是否可以在页面中看到以下文本

The content 'N° 1', of type 'ISAI', has been created.

在这里,我想把 N°1 放在通配符中,所以我只需要查找

"The content '/^[A-Z]{1}°[0-9]+$/', of type 'ISAI', has been created."

我开始创建如下所示的函数:

And I should see the text "The content 'WILDCARD', of type 'ISAI', has been created" with wildcard matching "/[a-zA-Z °]+$/"

/**
* @Then I should see the text :arg1 with wildcard matching :arg2
*/
public function iShouldSeeTheTextWithWildcardMatching($text, $regex){
  $string = str_replace('WILDCARD', $regex, $text);
  $result = $this->getSession()->getPage()->find('css', sprintf('div.alert-success:contains("%s")', $string));
  echo $result; // is null
}

但是,它失败了,因为选择器找不到任何带有“/”的东西(因为它是正则表达式)。

我的问题是:是否可以找到一些带有正则表达式的文本,我应该怎么做才能使我的方法起作用?

一些选项是:

一个
根据 2 部分文本创建一个选择器,并排除通配符中的内容。

//div[@class='alert-success'][contains(text(), 'The content')][contains(text(), 'of type \'ISAI\', has been created.')]

B
另一种解决方案是查看此元素的文本是否匹配。

步骤:
- 定义一个正则表达式
- 等待成功消息并获取文本
- 使用定义的正则表达式

检查保存的文本是否匹配

Your string/regex can be created using variables if needed. Use echo to mage sure your selector is valid. Make sure the page is loaded.