I am trying to write a function that builds a regular expression that can test whether a string starts with a string and contains another string.
function buildRegExp(startsWith,contains){
return new RegExp( ????? )
}
for example:
buildRegExp('abc','fg').test('abcdefg')
The above expression should evaluate to true, since the string 'abcdefg' starts with 'abc' and contains 'fg'.
The 'startsWith', and the 'contains' strings may overlap eachother, so the regular expression cannot simply search for the 'startsWith' string, then search for 'contains' string
the following should also evaluate to true:
buildRegExp('abc','bcd').test('abcdefg')
I cannot use simple string functions. It needs to be a regular expression because I am passing this regular expression to a MongoDB query.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.
A pattern like this would handle cases where the startsWith
/ contains
substrings overlap in the matched string:
/(?=.*bcd)^abc/
i.e.
return new RegExp("(?=.*" + contains + ")^" + startsWith);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With