RegEx完全匹配字符串的开头和结尾,中间带有通配符

时间:2022-11-24 15:24:17

I am searching strings with the following format: ABC-001

我正在使用以下格式搜索字符串:ABC-001

I would to construct a RegEx search from a user text input field so that I can search:

我想从用户文本输入字段构建一个RegEx搜索,以便我可以搜索:

ABC* and match ABC-001, ABC-002, and so on...
ABC*2 and match ABC-002 but NOT ABC-012
ABC*12 and match ABC-012

I know I will need do some string manipulation to go from user input to a regular expression, but as an example I construct a regex like so:

我知道我需要做一些字符串操作,从用户输入到正则表达式,但作为一个例子我构建一个像这样的正则表达式:

^ABC.*2$

Unfortunately, this matches ABC-002 and ABC-012.

不幸的是,这与ABC-002和ABC-012相匹配。

1 个解决方案

#1


0  

You can do this replace on user input:

您可以在用户输入上执行此替换:

var re = new RegExp(input.replace(/\*/g, '-0*'), "gi");

This will convert ABC*2 to /ABC-0*2/gi regex and this will match ABC-002 but won't match ABC-012.

这将ABC * 2转换为/ ABC-0 * 2 / gi正则表达式,这将匹配ABC-002,但不匹配ABC-012。

#1


0  

You can do this replace on user input:

您可以在用户输入上执行此替换:

var re = new RegExp(input.replace(/\*/g, '-0*'), "gi");

This will convert ABC*2 to /ABC-0*2/gi regex and this will match ABC-002 but won't match ABC-012.

这将ABC * 2转换为/ ABC-0 * 2 / gi正则表达式,这将匹配ABC-002,但不匹配ABC-012。