如何从字符串中删除电子邮件地址?

时间:2019-02-20 09:21:58

标签: regex autohotkey

所以,我有一个字符串,如果有,我想从中删除电子邮件地址。

例如:

  

这是一些文字,它继续像这样
  直到有时一封电子邮件   地址显示为asd@asd.com

     

这里和这里还有一些文字。

我想要这个结果。

  

这是一些文字,它继续像这样
  直到有时一封电子邮件   地址显示在[email_removed]

     

这里和这里还有一些文字。

cleanFromEmail(string)
{
    newWordString = 
    space := a_space
    Needle = @
    wordArray := StrSplit(string, [" ", "`n"])
    Loop % wordArray.MaxIndex()
    {

        thisWord := wordArray[A_Index]


        IfInString, thisWord, %Needle%
        {
            newWordString = %newWordString%%space%(email_removed)%space%
        }
        else
        {
            newWordString = %newWordString%%space%%thisWord%%space%
            ;msgbox asd
        }
    }

    return newWordString
}

问题是我最终失去了所有的换行符,只获得了空格。如何在删除电子邮件地址之前重建字符串,使其看起来像原来一样?

2 个答案:

答案 0 :(得分:3)

这看起来很复杂,为什么不使用RegExReplace呢?

string =
(
This is some text and it continues like this
until sometimes an email adress shows up asd@asd.com

also some more text here and here.
)

newWordString := RegExReplace(string, "\S+@\S+(?:\.\S+)+", "[email_removed]")

MsgBox, % newWordString

可以根据需要随意将样式简化或设为complicated,但是RegExReplace应该做到。

答案 1 :(得分:0)

如果由于某种原因RegExReplace并非始终为您工作,则可以尝试以下操作:

text =
(
This is some text and it continues like this
until sometimes an email adress shows up asd@asd.com.

also some more text here and here.
)

MsgBox, % cleanFromEmail(text)

cleanFromEmail(string){
    lineArray := StrSplit(string, "`n")
    Loop % lineArray.MaxIndex()
    {
        newLine := ""
        newWord := ""
        thisLine := lineArray[A_Index]
        If InStr(thisLine, "@")
        {
            wordArray := StrSplit(thisLine, " ")
            Loop % wordArray.MaxIndex()
            {
                thisWord := wordArray[A_Index]
                {
                    If InStr(thisWord, "@")
                    {
                        end := SubStr(thisWord, 0)
                        If end in ,,,.,;,?,!
                            newWord := "[email_removed]" end ""
                        else
                            newWord := "[email_removed]"
                    }
                    else
                        newWord := thisWord
                }
                newLine .= newWord . " " ; concatenate the outputs by adding a space to each one
            }
            newLine :=  trim(newLine) ; remove the last space from this variable
        }
        else
            newLine := thisLine
        newString .= newLine . "`n"
    }
    newString := trim(newString)
    return newString
}