簡體   English   中英

R中的正則表達式,表示兩個字符之間可變長度的單詞

[英]regular expression in R for word of variable length between two characters

如何從下面的字符串中提取單詞wordofvariablelength。

<a href=\"http://www.adrive.com/browse/wordofvariablelength\" class=\"next-button\" id=\"explore-gutter\" data-linkid=\"huiazc\"> <strong class=\"text gutter-text \">

我能夠使用下面的代碼獲取字符串的第一部分,但是有一個正則表達式,我可以使用它在“browse /”之后和“\\”之前立即獲取單詞,這里是單詞“wordofvariablelength” “使用下面的代碼

mystring = substr(mystring,nchar("<a href=\"http://www.thesaurus.com/browse/")+1,nchar("<a href=\"http://www.thesaurus.com/browse/")+20)

請注意,wordofvariablelength這個詞可以是任意長度,所以我不能硬編碼,開始和結束

嘗試

sub('.*?\\.com/[^/]*\\/([a-z]+).*', '\\1', mystring)
#[1] "wordofvariablelength"

要么

library(stringr)
 str_extract(mystring, perl('(?<=browse/)[A-Za-z]+'))
#[1] "wordofvariablelength"

數據

mystring <- "<a href=\"http://www.adrive.com/browse/wordofvariablelength\" class=\"next-button\" id=\"explore-gutter\" data-linkid=\"huiazc\"> <strong class=\"text gutter-text \">"

通過regmatches功能。

> x <- "<a href=\"http://www.adrive.com/browse/wordofvariablelength\" class=\"next-button\" id=\"explore-gutter\" data-linkid=\"huiazc\"> <strong class=\"text gutter-text \">"
> regmatches(x, regexpr('.*?"[^"]*/\\K[^/"]*(?=")', x, perl=TRUE))
[1] "wordofvariablelength"

要么

> regmatches(x, regexpr('[^/"]*(?="\\s+class=")', x, perl=TRUE))
[1] "wordofvariablelength"

要么

使用gsub更加簡單。

> gsub('.*/|".*', "", x)
[1] "wordofvariablelength"

你可以使用這個正則表達式

/browse\/(.*?)\\/g

這里演示https://regex101.com/r/gX4dC0/1

您可以使用以下正則表達式(?<=browse/).*?(?=\\\\") 。正則表達式表示:檢查我們是否有browse/ ,然后將所有后續字符最多(但不消耗) \\

示例代碼(以及此處示例程序 ):

mystr <- "<a href=\"http://www.adrive.com/browse/wordofvariablelength\" class=\"next-button\" id=\"explore-gutter\" data-linkid=\"huiazc\"> <strong class=\"text gutter-text \">"
regmatches(mystr, regexpr('(?<=browse/).*?(?=\\")', mystr, perl=T))

perl=T意味着我們使用類似Perl的正則表達式風格允許使用固定寬度的后視( (?<=browse/) )。

輸出:

[1] "wordofvariablelength"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM