2012-08-24 17 views
9

我匹配和替換之前和之後的空白4位數字:正則表達式匹配的一切,這不是一個4位數字

str12 <- "coihr 1234 &/()= jngm 34 ljd" 
sub("\\s\\d{4}\\s", "", str12) 
[1] "coihr&/()= jngm 34 ljd" 

但是,每次嘗試反轉這一併提取號碼,而不是失敗。 我想:

[1] 1234 

是否有人有線索?

PS:我知道如何與{stringr}做到這一點,但我想知道是否有可能與{基地}僅..

require(stringr) 
gsub("\\s", "", str_extract(str12, "\\s\\d{4}\\s")) 
[1] "1234" 

回答

5

這是可能的捕獲組使用()在正則表達式。以相同的例子

str12 <- "coihr 1234 &/()= jngm 34 ljd" 
gsub(".*\\s(\\d{4})\\s.*", "\\1", str12) 
[1] "1234" 
+0

@JoshObrien:只是意識到我們得到相同的解決方案... – dickoa

+0

是的。我們必須同時輸入相同的內容......我剛剛刪除了第一次嘗試,併發布了第二個更好的解決方案,它可以提取第一場比賽。 –

+0

謝謝,這有幫助! – Kay

0

我很天真一般的正則表達式,但這裏是一個醜陋的方式在基地:

# if it's always in the same spot as in your example 
unlist(strsplit(str12, split = " "))[2] 

# or if it can occur in various places 
str13 <- unlist(strsplit(str12, split = " ")) 
str13[!is.na(as.integer(str13)) & nchar(str13) == 4] # issues warning 
6

regmatches(),唯一可用的自R-2.14.0,讓你「提取物或替換從由regexprgregexprregexec獲得匹配數據匹配的子串」

下面是示例如何使用regmatches()來提取輸入字符串中的第一個空白緩衝的4位子字符串,或全部這樣的子字符串。

## Example strings and pattern 
x <- "coihr 1234 &/()= jngm 34 ljd"   # string with 1 matching substring 
xx <- "coihr 1234 &/()= jngm 3444 6789 ljd" # string with >1 matching substring 
pat <- "(?<=\\s)(\\d{4})(?=\\s)" 

## Use regexpr() to extract *1st* matching substring 
as.numeric(regmatches(x, regexpr(pat, x, perl=TRUE))) 
# [1] 1234 
as.numeric(regmatches(xx, regexpr(pat, xx, perl=TRUE))) 
# [1] 1234 


## Use gregexpr() to extract *all* matching substrings 
as.numeric(regmatches(xx, gregexpr(pat, xx, perl=TRUE))[[1]]) 
# [1] 1234 3444 6789 

(請注意,這將返回numeric(0)不包含子符合條件的字符串)。

+0

@JoshObrien:+1 regassches'的不錯用法 – dickoa

+0

我已經用dickoa的答案去了..不過,非常感謝發佈這種方法+1! – Kay

+0

這裏的另一個選擇是使用'\ b \\ d {4} \ b' - 如果數字在字符串的起始處,它也會起作用。 (但是,它也會匹配其他情況,如'「abc(1234)」')。當然,OP會說「前後有空白」,所以可能沒用':P' – Kobi

相關問題