开发者

Regular expression including wildcard character in search string

开发者 https://www.devze.com 2023-03-22 12:43 出处:网络
I want a regu开发者_JAVA技巧lar expression for a string This string can contain * and ? in it. But should have at least 3 alphanumeric character in it.

I want a regu开发者_JAVA技巧lar 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


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 combination means "at least 3 chars".

0

精彩评论

暂无评论...
验证码 换一张
取 消