2013-05-06 34 views
4

所以我有一個非常長的字符串,我想用多個匹配。我似乎只能使用regexpr獲得第一場比賽的第一名。我怎樣才能在同一個字符串中獲得多個職位(更多匹配)?R中的一個字符串中有多個正則表達式

我正在尋找html源代碼中的特定字符串。拍賣的標題(在html標籤之間)。它prooves那種不難發現:

到目前爲止,我用這個:

locationstart <- gregexpr("<span class=\"location-name\">", URL)[[1]]+28 
locationend <- regexpr("<", substring(URL, locationstart[1], locationend[1] + 100)) 
substring(URL, locationstart[1], locationstart[1] + locationend - 2) 

也就是說,我找了一個標題之前出現的一部分,然後我抓住那個地方,從那裏找表示標題結束的「<」。我願意提供更具體的建議。

+0

您可以發佈您的正則表達式? – 2013-05-06 15:31:26

+2

'?gregexpr'應該這樣做。 – Arun 2013-05-06 15:33:04

+0

@ SimonO101,我認爲這意味着'全球'...!?! – Arun 2013-05-06 15:34:17

回答

5

使用gregexpr允許多個匹配。

> x <- c("only one match", "match1 and match2", "none here") 
> m <- gregexpr("match[0-9]*", x) 
> m 
[[1]] 
[1] 10 
attr(,"match.length") 
[1] 5 
attr(,"useBytes") 
[1] TRUE 

[[2]] 
[1] 1 12 
attr(,"match.length") 
[1] 6 6 
attr(,"useBytes") 
[1] TRUE 

[[3]] 
[1] -1 
attr(,"match.length") 
[1] -1 
attr(,"useBytes") 
[1] TRUE 

,如果你正在尋找解壓就可以使用regmatches這樣做對你的比賽。

> regmatches(x, m) 
[[1]] 
[1] "match" 

[[2]] 
[1] "match1" "match2" 

[[3]] 
character(0) 
+0

令人驚歎。正是我在找什麼,還有更多(增加regmatches)。也很有趣,我只是一封信... – PascalVKooten 2013-05-06 16:55:01

1

gregexprregmatches的建議在達誠的回答允許提取字符串中的正則表達式模式的多個實例。此外,該解決方案的優勢在於完全依賴於R的{base}包,而不需要額外的包。

從來沒有少,我想建議基礎上,stringr package的替代解決方案。一般來說,這個包通過提供基本R的各種字符串支持函數(不僅僅是正則表達式相關的函數)的大部分功能,以及直觀地命名並提供一致性的一組函數API。事實上,stringr函數不僅僅是取代了基函數,但是在許多情況下引入了額外的特性;例如,字符串的正則表達式相關函數向量化爲字符串的模式。

特別針對在長字符串中提取多個圖案的問題,可以使用str_extract_allstr_match_all,如下所示。根據不同的事實,即輸入是一個字符串或它的一個向量,該邏輯可適於使用列表/矩陣標,unlist或其他方法,如lapplysapply等的點被該stringr函數返回結構,其可以被用來訪問我們想要的東西。

# simulate html input. (Using bogus html tags to mark the target texts; the demo works 
# the same for actual html patterns, the regular expression is just a bit more complex. 
htmlInput <- paste("Lorem ipsum dolor<blah>MATCH_ONE<blah> sit amet, purus", 
       "sollicitudin<blah>MATCH2<blah>mauris, <blah>MATCH Nr 3<blah>vitae donec", 
       "risus ipsum, aenean quis, sapien", 
       "in lorem, condimentum ornare viverra", 
       "suscipit <blah>LAST MATCH<blah> ipsum eget ac. Non senectus", 
       "dolor mauris tellus, dui leo purus varius") 

# str_extract() may need a bit of extra work to remove the leading and trailing parts 
str_extract_all(htmlInput, "(<blah>)([^<]+)<") 
# [[1]] 
# [1] "<blah>MATCH_ONE<" "<blah>MATCH2<"  "<blah>MATCH Nr 3<" "<blah>LAST MATCH<" 

str_match_all(htmlInput, "<blah>([^<]+)<")[[1]][, 2] 
# [1] "MATCH_ONE" "MATCH2"  "MATCH Nr 3" "LAST MATCH" 
相關問題