[英]Regex expression to remove start to end of character in string
I have this 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"
And I would like to splice this string from the start until after the "Subject" line so I get the email body content. 并且我想从头开始拼接该字符串,直到“主题”行之后,以便获得电子邮件正文内容。
I've tried this so far: 到目前为止,我已经尝试过了:
string.substring(string.lastIndexOf('Subject'), string.length - 1)
But this option does return the Subject line as well from the string. 但是此选项的确从字符串中返回主题行。
Is there a regex library I can use? 我可以使用正则表达式库吗?
Using string.replace
you can do: 使用string.replace
可以执行以下操作:
var body = string.replace(/^[\s\S]*\s+Subject: [^\n]*\n+/, '')
Code: 码:
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]*
matches 0 or more of any characters including newline. [\\s\\S]*
匹配0个或多个任何字符,包括换行符。 It is followed by Subject:
line which is also removed. 紧随其后的是Subject:
行。
Output: 输出:
"Hi Mark,
<br />
I'm sending this email as a way to test the email!
<br />
Cheers,
<br />
Jeremy"
Someone will give you the non-regex solution, but here is one with regex 有人会给您非正则表达式的解决方案,但这是一个带有正则表达式的解决方案
[\s\S]*Subject\s*:.*([\s\S]+) <-- your result in first capturing group
JS Demo 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>");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.