Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

javascript - JavaScript正则表达式多行标志不起作用(JavaScript regex multiline flag doesn't work)

I wrote a regex to fetch string from HTML, but it seems the multiline flag doesn't work.(我写了一个正则表达式从HTML中获取字符串,但似乎多行标志不起作用。)

This is my pattern and I want to get the text in h1 tag.(这是我的模式,我想在h1标签中获取文本。) var pattern= /<div class="box-content-5">.*<h1>([^<]+?)</h1>/mi m = html.search(pattern); return m[1]; I created a string to test it.(我创建了一个字符串来测试它。) When the string contains "\n", the result is always null.(当字符串包含“\ n”时,结果始终为null。) If I removed all the "\n"s, it gave me the right result, no matter with or without the /m flag.(如果我删除了所有“\ n”,它给了我正确的结果,无论是否带有/m标志。) What's wrong with my regex?(我的正则表达式有什么问题?)   ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are looking for the /.../s modifier, also known as the dotall modifier.(您正在寻找/.../s修饰符,也称为dotall修饰符。)

It forces the dot .(它强迫点.) to also match newlines, which it does not do by default.(也匹配换行符,默认情况下不会这样做 。) The bad news is that it does not exist in JavaScript (it does as of ES2018, see below) .(坏消息是它在JavaScript中不存在 (从ES2018开始,见下文) 。) The good news is that you can work around it by using a character class (eg \s ) and its negation ( \S ) together, like this:(好消息是你可以通过使用一个字符类(例如\s )和它的否定( \S )来解决它,如下所示:) [sS] So in your case the regex would become:(所以在你的情况下,正则表达式将成为:) /<div class="box-content-5">[sS]*<h1>([^<]+?)</h1>/i As of ES2018, JavaScript supports the s (dotAll) flag, so in a modern environment your regular expression could be as you wrote it, but with an s flag at the end (rather than m ; m changes how ^ and $ work, not . ):(从ES2018开始,JavaScript支持s (dotAll)标志,所以在现代环境中你的正则表达式可能就像你写的一样,但最后有一个s标志(而不是m ; m改变^$工作方式,而不是. ):) /<div class="box-content-5">.*<h1>([^<]+?)</h1>/is

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...