0

次のフレーズからメール アドレスを取得できないようです。

"mailto:fwwrp-3492801490@yahoo.com?"

これまで私は試しました

regexpr(":([^\\?*]?)", phrase)

コードのロジックは次のとおりです。

  1. セミコロン文字で開始します:
  2. 疑問符ではないすべての文字を取得します
  3. かっこ内の文字を返します。

正規表現のどこが間違っているのかわかりません。

4

2 に答える 2

9

正規表現を見てみましょう。どこが間違っているかがわかります。話しやすくするために、次のように分解します。

:            Just a literal colon, no worries here.
(            Open a capture group.
    [        Open a character class, this will match one character.
        ^    The leading ^ means "negate this class"
        \\   This ends up as a single \ when the regex engine sees it and that will
             escape the next character.
        ?    This has no special meaning inside a character class, sometimes a
             question mark is just a question mark and this is one of those
             times. Escaping a simple character doesn't do anything interesting.
        *    Again, we're in a character class so * has no special meaning.
    ]        Close the character class.
    ?        Zero or one of the preceding pattern.
)            Close the capture group.

ノイズを取り除くと、 が得られ:([^?*]?)ます。

したがって、正規表現は実際に一致します:

コロンの後に疑問符またはアスタリスク以外の 0 個または 1 個の文字が続き、その非疑問符または非アスタリスクは最初のキャプチャ グループに含まれます。

それはあなたがやろうとしていることのようなものではありません。いくつかの調整で解決するはずです:

:([^?]*)

それは一致します:

コロンの後に任意の数の非疑問符が続き、非疑問符は最初のキャプチャ グループになります。

文字クラスの*外側は特別で、文字クラスの外側は「ゼロ以上」を意味し、文字クラスの内側は単なる*.

R の側面については他の人に任せます。正規表現で何が起こっているのかを理解してもらいたいだけです。

于 2012-12-24T05:22:05.963 に答える
3

を使用した非常に簡単なアプローチを次に示しgsubます。

gsub("([a-z]+:)(.*)([?]$)", "\\2", "mailto:fwwrp-3492801490@yahoo.com?")
## Or, if you expect things other than characters before the colon
gsub("(.*:)(.*)([?]$)", "\\2", "mailto:fwwrp-3492801490@yahoo.com?")
## Or, discarding the first and third groups since they aren't very useful
gsub(".*:(.*)[?]$", "\\1", "mailto:fwwrp-3492801490@yahoo.com?")

@TylerRinker が開始した場所から構築すると、strsplit次のように使用することもできます (疑問符を消す必要がなくなりますgsub)。

strsplit("mailto:fwwrp-3492801490@yahoo.com?", ":|\\?", fixed=FALSE)[[1]][2]

そのような文字列のリストがあればどうでしょうか?

phrase <- c("mailto:fwwrp-3492801490@yahoo.com?", 
            "mailto:somefunk.y-address@Sqmpalm.net?")
phrase
# [1] "mailto:fwwrp-3492801490@yahoo.com?"  
# [2] "mailto:somefunk.y-address@Sqmpalm.net?"

## Using gsub
gsub("(.*:)(.*)([?]$)", "\\2", phrase)
# [1] "fwwrp-3492801490@yahoo.com"     "somefunk.y-address@Sqmpalm.net"

## Using strsplit
sapply(phrase, 
       function(x) strsplit(x, ":|\\?", fixed=FALSE)[[1]][2], 
       USE.NAMES=FALSE)
# [1] "fwwrp-3492801490@yahoo.com"     "somefunk.y-address@Sqmpalm.net"

gsub私はアプローチの簡潔さを好みます。

于 2012-12-24T05:03:22.477 に答える