如何在Regex中只删除(anyword).com?

use*_*897 0 regex r space

我想匹配以下内容

My best email gmail.com
email com
email.com
Run Code Online (Sandbox Code Playgroud)

成为

My best email
email com
*nothing*
Run Code Online (Sandbox Code Playgroud)

具体来说,我正在使用Regex for R,所以我知道有一些不同的规则来逃避某些字符.我对Regex很新,但到目前为止我都有

\ .*(com) 
Run Code Online (Sandbox Code Playgroud)

这使得相同的输入

My
Run Code Online (Sandbox Code Playgroud)

但是这个代码不适用于没有像第三个例子那样的空格的情况,并且如果该行有一个".com",则删除一行之后的所有内容.

Wik*_*żew 5

使用以下解决方案:

x <- c("My best email gmail.com","email com", "email.com", "smail.com text here")
trimws(gsub("\\S+\\.com\\b", "", x))
## => [1] "My best email" "email com"     ""              "text here"
Run Code Online (Sandbox Code Playgroud)

参见R演示.

\\S+\\.com\\b模式匹配1 +非空白字符,后跟字面.com后跟单词边界.

trimws函数将修剪所有结果字符串(例如"smail.com text here",当smail.com删除后仍留有空格时).

请注意,TRE正则表达式引擎不支持括号表达式中的速记字符类.