2014-01-12 13 views
3

我想匹配字符串前面不包含「hallo」的字符。如何在R中寫出表達`不包含'的模式?

>string <- c("halloman","hi","dancing","manhallomorning") 
>grep("hallo",string,invert=TRUE) 
[1] 2 3 
grep("(?<!hallo)\\w+",string,perl=TRUE) 
[1] 1 2 3 4 #the result is 2 3 which do not contain "hallo" . 

如何修改表達不包含hallo的格局?

+0

我更新了答案。一探究竟。順便說一句,爲什麼你不使用'invert = TRUE'? – falsetru

+0

親愛的falsetru,'invert = TRUE'只能在R中使用,'^((?! hallo)。)* $'可以更廣泛地使用。 –

回答

2

使用負向預測。指定^僅匹配字符串的開頭。

> string <- c("halloman", "hi", "dancing") 
> grep("^(?!hallo)", string, perl=TRUE) 
[1] 2 3 

UPDATE accoridng的問題編輯。

> string <- c("halloman","hi","dancing","manhallomorning") 
> grep("^((?!hallo).)*$", string, perl=TRUE) 
[1] 2 3 
1

您可能不需要負面預測。這將做的工作:

> grep("^hallo",string,invert=TRUE) 
[1] 2 3 

即的

^ = at the beginning of the string, 
invert=TRUE to return elements that do NOT match 

的組合就足夠了。

如果你堅持使用負先行,這工作,也:

> grep("^(?!hallo)", string, perl=TRUE) 
[1] 2 3 

我用排除模式,而不是回顧後,再次使用^錨。

相關問題