最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regular expression including wildcard character in search string - Stack Overflow

programmeradmin9浏览0评论

I want a regular expression for a string This string can contain * and ? in it. But should have at least 3 alphanumeric character in it. So,

*abc* is valid
*ab*c is valid
*aaa? is valid
*aa  is not valid
**aaa is not valid as it is not a valid regular expression

I want a regular expression for a string This string can contain * and ? in it. But should have at least 3 alphanumeric character in it. So,

*abc* is valid
*ab*c is valid
*aaa? is valid
*aa  is not valid
**aaa is not valid as it is not a valid regular expression
Share Improve this question edited Jul 21, 2011 at 13:27 Kirill Polishchuk 56.2k11 gold badges124 silver badges126 bronze badges asked Jul 21, 2011 at 13:24 NitsNits 9014 gold badges15 silver badges30 bronze badges 3
  • 4 So do you want a regular expression for a regular expression or what you described? Because your last ment '*aaa is not valid as it is not a valid regular expression' doesn't line up with '*abc is valid'. – Chris Pfohl Commented Jul 21, 2011 at 13:28
  • I mean *aaa is valid while **aaa(2 continuous astrixs) is not valid, as we even don't write this kind of string in regular expression also. – Nits Commented Jul 21, 2011 at 13:43
  • 1 So how is *abc* a valid regex, then? – Tim Pietzcker Commented Jul 21, 2011 at 13:46
Add a ment  | 

3 Answers 3

Reset to default 5

This should do it:

^[*?]?([0-9a-z][*?]?){3,}$

Explanation:

  • ^ matches the beginning of the string
  • [*?]? matches an optional * or ?
  • (...){3,} the group must appear at least 3 times
  • [0-9a-z][*?]? matches an alphanumeric character followed by an optional * or ?
  • $ matches the end of the string

Consecutive * and ? are not matched.

Update: Forgot to mention it, but it was on my mind: Use i modifier to make the match case-insensitive (/.../i).

can use regex and implment it in javascript

var searchin = item.toLowerCase();
var str = "*abc*";
str = str.replace(/[*]/g, ".*").toLowerCase().trim();
return new RegExp("^"+ str + "$").test(searchin);

Since I'm guessing that ? represents any one character and * any number of characters, and that you want to disallow consecutive *, but not consecutive ? (so that file.??? would be valid, representing file. followed by three chars, eg file.txt), and allow other content than just [A-Za-z\d*?]:

/^(?!.*\*\*)(?:[^a-z\d]*[a-z\d]){3,}[^a-z\d]*/i

Assuming that file.???* should be valid too, since this bination means "at least 3 chars".

发布评论

评论列表(0)

  1. 暂无评论