Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for string starts with X and contains Y

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.

like image 379
Will Olsen Avatar asked Sep 29 '13 04:09

Will Olsen


People also ask

What does \+ mean in regex?

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 "(" .

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

What does regex 0 * 1 * 0 * 1 * Mean?

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.


1 Answers

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);
like image 150
p.s.w.g Avatar answered Oct 09 '22 17:10

p.s.w.g