字符串的正则表达式以X开头并包含Y. [英] regex for string starts with X and contains Y

查看:95
本文介绍了字符串的正则表达式以X开头并包含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( ????? )
}

例如:

buildRegExp('abc','fg').test('abcdefg')

上面的表达式应该评估为true,因为字符串'abcdefg'以''开头' abc'并包含'fg'。

The above expression should evaluate to true, since the string 'abcdefg' starts with 'abc' and contains 'fg'.

'startsWith'和'contains'字符串可能相互重叠,因此正则表达式不能简单地搜索'startsWith'字符串,然后搜索'contains'字符串

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

以下内容也应评估为true:

the following should also evaluate to true:

buildRegExp('abc','bcd').test('abcdefg')

我不能使用简单的字符串函数。它需要是一个正则表达式,因为我将这个正则表达式传递给MongoDB查询。

I cannot use simple string functions. It needs to be a regular expression because I am passing this regular expression to a MongoDB query.

推荐答案

这样的模式会处理 startsWith / 包含匹配字符串中的子字符串重叠的情况:

A pattern like this would handle cases where the startsWith / contains substrings overlap in the matched string:

/(?=.*bcd)^abc/

ie

return new RegExp("(?=.*" + contains + ")^" + startsWith);

这篇关于字符串的正则表达式以X开头并包含Y.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆