次のフレーズからメール アドレスを取得できないようです。
"mailto:fwwrp-3492801490@yahoo.com?"
これまで私は試しました
regexpr(":([^\\?*]?)", phrase)
コードのロジックは次のとおりです。
- セミコロン文字で開始します:
- 疑問符ではないすべての文字を取得します
- かっこ内の文字を返します。
正規表現のどこが間違っているのかわかりません。
正規表現を見てみましょう。どこが間違っているかがわかります。話しやすくするために、次のように分解します。
: 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 の側面については他の人に任せます。正規表現で何が起こっているのかを理解してもらいたいだけです。
を使用した非常に簡単なアプローチを次に示し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
私はアプローチの簡潔さを好みます。