r语言 - 用in{}匹配任何模式



我使用R,我有以下文本:

text<-"nnnnnThe Project Gutenberg eBook of Moby Dick; Or the Whale, by Herman Melvillennnn    body {margin-left:15%; margin-right:15%; text-align:justify }n    p { text-indent: 1em; margin-top: .25em; margin-bottom: .25em; }n    H1,H2,H3,H4,H5,H6 { text-align: center; margin-left: 15%; margin-right: 15%; }n    hr  { width: 50%; text-align: center;}n    blockquote {font-size: 100%; margin-left: 0%; margin-right: 0%;}n    .mynote    {background-color: #DDE; color: #000; padding: .5em; margin-left: 10%; margin-right: 10%; font-family: sans-serif; font-size: 95%;}n    .toc       { margin-left: 10%; margin-bottom: .75em;}n    pre        { font-family: times new roman; font-size: 100%; margin-left: 10%;}nn"

我想删除{}中的所有模式和所有以。

开头的单词以为例,我希望删除以下内容:"{margin-left: 15%;margin-right: 15%;text-align:证明}";.toc.25em

尝试以下regex:

gsub('{.*?}', "",text)
gsub('^[.]w*', "",text)

但是R返回错误。

需要转义regex元字符,如{。根据R的正则表达式文档:

任何有特殊意义的元字符都可以用反斜杠加引号。扩展正则表达式中的元字符是' -。 |()[{^ $ * + ? $ $ ',但请注意这些是否具有特殊含义取决于上下文。

除此之外,你的模式还有一些问题。考虑使用这个版本:
text <- "nnnnnThe Project Gutenberg eBook of Moby Dick; Or the Whale, by Herman Melvillennnn    body {margin-left:15%; margin-right:15%; text-align:justify }n    p { text-indent: 1em; margin-top: .25em; margin-bottom: .25em; }n    H1,H2,H3,H4,H5,H6 { text-align: center; margin-left: 15%; margin-right: 15%; }n    hr  { width: 50%; text-align: center;}n    blockquote {font-size: 100%; margin-left: 0%; margin-right: 0%;}n    .mynote    {background-color: #DDE; color: #000; padding: .5em; margin-left: 10%; margin-right: 10%; font-family: sans-serif; font-size: 95%;}n    .toc       { margin-left: 10%; margin-bottom: .75em;}n    pre        { font-family: times new roman; font-size: 100%; margin-left: 10%;}nn"
text <- gsub('\{.*?\}|(?<!\S)\.\S+', "", text, perl=TRUE)
text
[1] "nnnnnThe Project Gutenberg eBook of Moby Dick; Or the Whale, by Herman Melvillennnn    body n    p n    H1,H2,H3,H4,H5,H6 n    hr  n    blockquote n        n           n    pre        nn"

注意,我也转义了},尽管它不是必需的。有些正则表达式需要这样做,从可移植性的角度来看,转义{}可能有好处。

相关内容

最新更新