Will Olsen
Will Olsen

Reputation: 335

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.

Upvotes: 5

Views: 13566

Answers (2)

Teemu Ikonen
Teemu Ikonen

Reputation: 11929

Try this regexp

(^X).*Y

E.g. in javascript

/(^ab).*bc/.test('abc') => false

/(^ab).*bc/.test('abcbc') => true

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 149050

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);

Upvotes: 9

Related Questions