正则表达式 - 如何匹配非单词字符的边界?

时间:2013-03-27 22:02:07

标签: regex preg-replace

我需要匹配以下内容:

-foo
foo-

但我不想匹配foo-bar

我无法使用\b,因为它与连字符的边界不匹配。我的目标是用空格替换连字符。建议?

更新1 (更好的例子):

xxx yyy -foo foo- foo-bar zzz

我只对字符串-foofoo-感兴趣。想法是删除那些连字符。连字符用于连字。意思是,左右应该有一个词。如果没有,则不应出现连字符。

2 个答案:

答案 0 :(得分:1)

具有负前瞻和后视的解决方案:

$string = 'xxx yyy -removethis andthis- foo-bar zzz -andalsothis-';
$new_string = preg_replace('/(?<!\w)-(\w+)-(?!\w)|(?<!\w)-(\w+)|(\w+)-(?!\w)/', '$1$2$3', $string);
echo $new_string; // Output: xxx yyy removethis andthis foo-bar zzz andalsothis

/*
   (?<!\w) : Check if there is a \w behind, if there is a \w then don't match.
   (?!\w) : Check if there is a \w ahead, if there is a \w then don't match.
   \w : Any word character (letter, number, underscore)
*/

Online demo

答案 1 :(得分:0)

我的解决方案:^-|-$| -|-

Match either the regular expression below (attempting the next alternative only if this one fails) «^-»
   Assert position at the beginning of the string «^»
   Match the character “-” literally «-»
Or match regular expression number 2 below (attempting the next alternative only if this one fails) «-$»
   Match the character “-” literally «-»
   Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
Or match regular expression number 3 below (attempting the next alternative only if this one fails) « -»
   Match the characters “ -” literally « -»
Or match regular expression number 4 below (the entire match attempt fails if this one fails to match) «- »
   Match the characters “- ” literally «- »
相关问题