用于删除字符串中字符开头到结尾的正则表达式
Regex expression to remove start to end of character in string
我有这个字符串:
var string = "From: Jeremy<br />
Sent: 22 Apr 2016 12:08:03</br />
To: Mark<br />
Subject: Another test email<br /><br />
Hi Mark,
<br />
I'm sending this email as a way to test the email!
<br />
Cheers,
<br />
Jeremy"
我想从头开始拼接这个字符串,直到 "Subject" 行之后,这样我才能得到电子邮件正文内容。
到目前为止我已经试过了:
string.substring(string.lastIndexOf('Subject'), string.length - 1)
但是这个选项 return 主题行也来自字符串。
有我可以使用的正则表达式库吗?
使用string.replace
你可以做到:
var body = string.replace(/^[\s\S]*\s+Subject: [^\n]*\n+/, '')
代码:
var string = `From: Jeremy<br />
Sent: 22 Apr 2016 12:08:03</br />
To: Mark<br />
Subject: Another test email<br /><br />
Hi Mark,
<br />
I'm sending this email as a way to test the email!
<br />
Cheers,
<br />
Jeremy`
var body = string.replace(/^[\s\S]*\s+Subject: [^\n]*\n+/, '')
document.writeln("<pre>" + body + "</pre>")
[\s\S]*
匹配 0 个或多个任意字符,包括换行符。紧随其后的 Subject:
行也被删除。
输出:
"Hi Mark,
<br />
I'm sending this email as a way to test the email!
<br />
Cheers,
<br />
Jeremy"
有人会给你非正则表达式的解决方案,但这里有一个带有正则表达式的解决方案
[\s\S]*Subject\s*:.*([\s\S]+) <-- your result in first capturing group
JS 演示
var re = /[\s\S]*Subject\s*:.*([\s\S]+)/gm;
var str = `From: Jeremy<br />
Sent: 22 Apr 2016 12:08:03</br />
To: Mark<br />
Subject: Another test email<br /><br />
Hi Mark,
<br />
I'm sending this email as a way to test the email!
<br />
Cheers,
<br />
Jeremy`
var m = re.exec(str);
document.writeln("<pre>" + m[1] + "</pre>");
我有这个字符串:
var string = "From: Jeremy<br />
Sent: 22 Apr 2016 12:08:03</br />
To: Mark<br />
Subject: Another test email<br /><br />
Hi Mark,
<br />
I'm sending this email as a way to test the email!
<br />
Cheers,
<br />
Jeremy"
我想从头开始拼接这个字符串,直到 "Subject" 行之后,这样我才能得到电子邮件正文内容。
到目前为止我已经试过了:
string.substring(string.lastIndexOf('Subject'), string.length - 1)
但是这个选项 return 主题行也来自字符串。
有我可以使用的正则表达式库吗?
使用string.replace
你可以做到:
var body = string.replace(/^[\s\S]*\s+Subject: [^\n]*\n+/, '')
代码:
var string = `From: Jeremy<br />
Sent: 22 Apr 2016 12:08:03</br />
To: Mark<br />
Subject: Another test email<br /><br />
Hi Mark,
<br />
I'm sending this email as a way to test the email!
<br />
Cheers,
<br />
Jeremy`
var body = string.replace(/^[\s\S]*\s+Subject: [^\n]*\n+/, '')
document.writeln("<pre>" + body + "</pre>")
[\s\S]*
匹配 0 个或多个任意字符,包括换行符。紧随其后的 Subject:
行也被删除。
输出:
"Hi Mark,
<br />
I'm sending this email as a way to test the email!
<br />
Cheers,
<br />
Jeremy"
有人会给你非正则表达式的解决方案,但这里有一个带有正则表达式的解决方案
[\s\S]*Subject\s*:.*([\s\S]+) <-- your result in first capturing group
JS 演示
var re = /[\s\S]*Subject\s*:.*([\s\S]+)/gm;
var str = `From: Jeremy<br />
Sent: 22 Apr 2016 12:08:03</br />
To: Mark<br />
Subject: Another test email<br /><br />
Hi Mark,
<br />
I'm sending this email as a way to test the email!
<br />
Cheers,
<br />
Jeremy`
var m = re.exec(str);
document.writeln("<pre>" + m[1] + "</pre>");