JavaScript 正则表达式多行标志不起作用 [英] JavaScript regex multiline flag doesn't work

查看:36
本文介绍了JavaScript 正则表达式多行标志不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个正则表达式来从 HTML 中获取字符串,但似乎多行标志不起作用.

这是我的模式,我想获取 h1 标签中的文本.

var pattern=/

.*

([^<]+?)

/mim = html.search(模式);返回 m[1];

我创建了一个字符串来测试它.当字符串包含 "时,结果始终为空.如果我删除了所有的 ",它给了我正确的结果,不管有没有 /m 标志.

我的正则表达式有什么问题?

解决方案

您正在寻找 /.../s 修饰符,也称为 dotall 修饰符.它强制点 . 也匹配换行符,默认情况下它不这样做.

坏消息是它在 JavaScript 中不存在 (它在 ES2018 中存在,见下文).好消息是,您可以通过同时使用字符类(例如 s)及其否定(S)来解决它,如下所示:

[sS]

所以在你的情况下,正则表达式会变成:

/

[sS]*

([^<]+?)

/i

<小时>

从 ES2018 开始,JavaScript 支持 s (dotAll) 标志,因此在现代环境中,您的正则表达式可能与您编写的一样,但带有 s 标志最后(而不是 m; m 改变了 ^$ 的工作方式,而不是 .):

/

.*

([^<]+?)

/is

I wrote a regex to fetch string from HTML, but it seems the multiline flag doesn't work.

This is my pattern and I want to get the text in h1 tag.

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 " ", the result is always null. If I removed all the " "s, it gave me the right result, no matter with or without the /m flag.

What's wrong with my regex?

解决方案

You are looking for the /.../s modifier, also known as the dotall modifier. 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). The good news is that you can work around it by using a character class (e.g. s) and its negation (S) together, like this:

[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 .):

/<div class="box-content-5">.*<h1>([^<]+?)</h1>/is

这篇关于JavaScript 正则表达式多行标志不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆