正则表达式匹配以连字符开头的单词

时间:2022-09-13 11:42:00

I have a regex which does all matches except one match.The PHP Code for the word match is:

我有一个正则表达式,它执行除一个匹配之外的所有匹配。单词匹配的PHP代码是:

$string = preg_replace("/\b".$wordToMatch."\b/","<span class='sp_err' style='background-color:yellow;'>".$wordToMatch."</span>",$string); 

Here in the above regex when the $wordToMatch variable value becomes "-abc" and the $string value is "The word -abc should match and abc-abc should not match".With above regex it fails to catch "-abc".

在上面的正则表达式中,当$ wordToMatch变量值变为“-abc”且$ string值为“-abc应该匹配且abc-abc不匹配时”。使用上面的正则表达式,它无法捕获“-abc”。

  • I want enhancement in the above regex so that it can catch "-abc" in $string,but if it tries to match "-abc" in "abc-abc" of $string it should not.
  • 我希望在上面的正则表达式中进行增强,以便它可以在$ string中捕获“-abc”,但如果它尝试匹配$ string的“abc-abc”中的“-abc”则不应该。

1 个解决方案

#1


1  

In case your keywords can have non-word characters on both ends you can rely on lookarounds for a whole word match:

如果您的关键字在两端都可以包含非单词字符,则可以依赖于整个单词匹配的外观:

"/(?<!\\w)".$wordToMatch."(?!\\w)/"

Here, (?<!\w) will make sure there is no word character before the word to match, and (?!\w) negative lookahead will make sure there is no word character after the word to match. These are unambiguous subpatterns, while \b meaning depends on the context.

在这里,(?<!\ w)将确保在匹配的单词之前没有单词字符,并且(?!\ w)否定前瞻将确保在单词匹配之后没有单词字符。这些是明确的子模式,而\ b意味着取决于上下文。

See regex demo showing that -abc is not matched in abc-abc and matches if it is not enclosed with word characters.

请参阅正则表达式演示,显示-abc在abc-abc中不匹配,如果未用单词字符括起,则匹配。

PHP demo:

PHP演示:

$wordToMatch = "-abc";
$re = "/(?<!\\w)" . $wordToMatch . "(?!\\w)/"; 
$str = "abc-abc -abc"; 
$subst = "!$0!"; 
$result = preg_replace($re, $subst, $str);
echo $result; // => abc-abc !-abc!

#1


1  

In case your keywords can have non-word characters on both ends you can rely on lookarounds for a whole word match:

如果您的关键字在两端都可以包含非单词字符,则可以依赖于整个单词匹配的外观:

"/(?<!\\w)".$wordToMatch."(?!\\w)/"

Here, (?<!\w) will make sure there is no word character before the word to match, and (?!\w) negative lookahead will make sure there is no word character after the word to match. These are unambiguous subpatterns, while \b meaning depends on the context.

在这里,(?<!\ w)将确保在匹配的单词之前没有单词字符,并且(?!\ w)否定前瞻将确保在单词匹配之后没有单词字符。这些是明确的子模式,而\ b意味着取决于上下文。

See regex demo showing that -abc is not matched in abc-abc and matches if it is not enclosed with word characters.

请参阅正则表达式演示,显示-abc在abc-abc中不匹配,如果未用单词字符括起,则匹配。

PHP demo:

PHP演示:

$wordToMatch = "-abc";
$re = "/(?<!\\w)" . $wordToMatch . "(?!\\w)/"; 
$str = "abc-abc -abc"; 
$subst = "!$0!"; 
$result = preg_replace($re, $subst, $str);
echo $result; // => abc-abc !-abc!