javascript - 如何在javascript正则表达式中匹配精确的字符串

标签 javascript php regex

我的 JavaScript 正则表达式是

/\[DEF\]([^\[\]]+)\[\/DEF\]/g  

我的字符串是

[DEF]sdgsdggsFfg sdgsdg[/DEF]

我想检查我的正则表达式,中间的[/DEF]没有出现,我该怎么办。

当我将此正则表达式修改为 /\[DEF\]([^\[\/DEF]]+)\[\/DEF\]/g 但在正则表达式中它匹配单个字符,例如 D、E 或 F 我想将其与精确的 [/DEF]

匹配

我能为它做什么。

最佳答案

这是简单的正则表达式:

/\[DEF\]([\s\S]*?)\[\/DEF\]/g

使其不区分大小写(def instaead of DEF)

/\[DEF\]([\s\S]*?)\[\/DEF\]/gi

你也可以做一个简单的:

/\[DEF\](.*?)\[\/DEF\]/

但它只支持 1 次出现,并且不支持多行匹配。

当我看到你的字符串时: /\[DEF\]([^\[\/DEF]]+)\[\/DEF\]/g 看起来你没有知道.*是什么意思吗?

The question mark after * makes it ungreedy. If you leave it out, it will match everything between the first WORD1 and the last WORD2 where if you have multiple occurences of WORD2 the ungreedy operator will only match until the first WORD2 http://forums.phpfreaks.com/topic/265751-how-does-it-work/

##示例

var source = 'Exampe Source[DEF]my source[/DEF]'
document.write(source + '<br>')
alert('Source: ' + source)
var match = source.match(/\[DEF\]([\s\S]*?)\[\/DEF\]/g)
alert('Match:' + match)
document.write(match + '<br>')

关于javascript - 如何在javascript正则表达式中匹配精确的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34155008/

相关文章:

用于具有特定字符顺序的强密码的 Javascript 正则表达式

javascript - RxJS 函数从一个 observable 发出最后一个值,然后另一个发出 true

javascript - 将 javascript 警报显示为 toast

php - 以编程方式删除数据库字段上的重复项

javascript - 从数据表结果中删除时间

javascript - 如何用正则表达式替换未知数量的相同字符?

javascript - 是否可以选择所有与选择器不匹配的元素?

javascript - Asp.NET 未获取 javascript 设置的自定义属性的更新值

php - 在 Grocery 店上传视频

正则表达式 - 字符串之前一年的第一个实例