仅当指定的字符串存在时,Regex返回true

Regex to return true only if the specified string is present

本文关键字:Regex 返回 true 存在 字符串      更新时间:2023-09-26

我尝试匹配"Test"

var regex = new RegExp('^((?!Test).)*$')
regex.test('Test')

然而,这不起作用。

我需要一个正则表达式,只有当指定的字符串存在时才返回true。

可以是^Test$,也可以是string === 'Test'

如果你想测试一个字符串是否存在,试试Test。使用JavaScript,您可以执行str.indexOf("Test") != -1。如果要测试字符串是否仅为test,请使用^Test$str === "Test"

如果您坚持使用断言来测试某个单词的存在:

/(?='bTest'b)/.test('I want to Test this')
// true
/(?='bTest'b)/.test('I want to Fail this')
// false