Reputation: 370
I'm making a discord bot using node.js and I wanted to add an anti spam feature to it. The goal is simple:
I would like to match, using regex preferably, the following sentence:
hello my name is anon hello my name is anon hello my name is anon hello my name is anon
Tho, I dont want it to match these strings:
hello my name is anon hello my name is anon hello my name is anon
hello my name is anon
hello, my name is anon hello my name is anon hello my name is anon hello my name is anon
(notice the comma at the start)
Of course, the few words im using here could be anything and thats were I need your help... Is regex able to do this? If so, how? I took a look at words boundaries and stuff but im pretty lost here...
Thanks in advance! :)
Upvotes: 3
Views: 886
Reputation: 110725
If you wish to identify strings of the form s s s sx
, where s
is a common substring and x
is any substring, you could use the regular expression
^(.+)(?: +\1){3}
The regex engine performs the following operations.
^ match beginning of line
(.*+) match any char other than newline, 1+ times,
saving to capture group 1
(?: +\1) match 1+ spaces followed by the content of
capture group 1 in a non-cap group
{3} execute non-cap group 3 times
Upvotes: 3
Reputation: 589
This problem reduces to finding a non-empty sequence, such that repeated x times equals the whole string.
I suggest a possible solution:
function checkRep(str){
return /^(.+?)\1+$/.test(str);
}
console.log(checkRep("example")); // false
console.log(checkRep("example example")); // false
console.log(checkRep("example example ")); // true
console.log(checkRep("example example hello")); // false
Notice that \1
is just a backreference to the match (.+?)
.
And in case you do not want to take whitespaces into account (recommended), you can use:
function checkRep(str){
return /^\s*(.+?)(\s*\1\s*)+$/.test(str);
}
console.log(checkRep("example")); // false
console.log(checkRep("example example")); // true
console.log(checkRep("example example ")); // true
console.log(checkRep("example example hello")); // false
Upvotes: 2