2013-03-27 82 views
2

我需要符合以下条件:正则表达式 - 如何匹配非单词字符的边界?

-foo 
foo- 

但我不希望匹配foo-bar。我不能使用\b,因为这不符合连字符的边界。我的目标是用一个空格替换连字符。建议?

更新1(最好的例子):

xxx yyy -foo foo- foo-bar zzz 

我只是在弦-foofoo-感兴趣。这个想法是删除这些连字符。连字符是连字。意思是说,它的左右应该有一个词。如果没有,则不应出现连字符。

+0

您将需要更具体地了解您想要接受的内容以及您想要拒绝的内容。另外,'\ b'只匹配一个字的边界,所以我只能假设你想用它作为一些较大模式的一部分。什么是更大的模式? – 2013-03-27 22:04:59

+0

我试图看看是否可以使用'\ b'来匹配连字符的开头。不行。我真的只需要匹配以连字符开头的字符串或以连字符结尾的字符串。 – StackOverflowNewbie 2013-03-27 22:12:57

+1

这很简单,然后,担心单词边界只是过分复杂的事情。你最初应该说的很多! – 2013-03-27 22:15:08

回答

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

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 «- »