At first, I thought the following regex wouldn't match anything, since it's empty:
const emptyText = ''
const regExp = new RegExp(`${emptyText}`)
console.log(regExp) // /(?:)/
const result = 'This shouldn\'t match'.match(regExp)
console.log(result)
But then I realized it will match everything, since everything can be /(?:)/
How to modify this regex (or code), so that an empty text (''
) doesn't match everything? And it matches nothing instead?
Current output:
[
""
]
Desired output:
null
CodePudding user response:
You can do something like the following:
const emptyText = '^$'
const regExp = new RegExp(`${emptyText}`)
console.log(regExp) // /(?:)/
const result = 'This shouldn\'t match'.match(regExp)
console.log(result)
Here:
^
matches the beginning of the string and $
matches the end of the string.
Note: the return value is null
, means that (null
) or "no value at all" is assigned to result
.
Update: In case we can't change emptyText
, we might concatenate another string inside RegExp
constructor like the following:
const emptyText = ''
const rx = '^$';
var regExp = new RegExp(`${emptyText}`)
if(emptyText === '') {
regExp = new RegExp(`${emptyText}${rx}`)
}
console.log(regExp) // /(?:)/
const result = 'This shouldn\'t match'.match(regExp)
console.log(result)
Here rx
is holding the regex value.
CodePudding user response:
To prevent an empty regex from matching everything, you can use a character class with a negated character range that matches any character that is not a digit, letter, or whitespace. This can be done by using the following regex:
const emptyText = ''
const regExp = new RegExp(`[^\d\w\s]${emptyText}[^\d\w\s]`)
console.log(regExp) // /[^\d\w\s](?:)[^\d\w\s]/
const result = 'This shouldn\'t match'.match(regExp)
console.log(result) // null
In this example, the character class [^\d\w\s] matches any character that is not a digit, letter, or whitespace. Since the empty string emptyText is placed between these two character classes, it will not match any characters in the input string. Therefore, the match method will return null because there are no matches in the input string.