Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for wild card search in javascript

I have a string as SEARCH0000123456 and SEARCH000096834 and a I want to perform below search using wildcard *

  1. SEARC*2*6 - should match SEARCH0000123456
  2. SEARC*9* - should match SEARCH000096834
  3. *123* - should match SEARCH0000123456
  4. *834 - should match SEARCH000096834

So, * is the wildcard which should match any character.

Is there any way we can achieve this using regular expression in javascript

Thanks

like image 447
Phantom Avatar asked Sep 06 '25 07:09

Phantom


2 Answers

Just replace * with .* to match zero or more characters in regex. Or .+ to match one or more characters. And also add anchors, because SEARC*2*6 glob pattern will match the strings only if it's starts with SEARC, so we need to use a starting anchor ^ here.

SEARC*2*6   - ^SEARC.*2.*6$
SEARC*9*    - ^SEARC.*9.*
*123*       - .*123.*
*834        - .*834$
SE.ARC*2*6  - ^SE\.ARC.*2.*6$
?E.ARC*2*6  - ^.E\.ARC.*2.*6$
like image 177
Avinash Raj Avatar answered Sep 09 '25 03:09

Avinash Raj


Mozilla have a good introduction to JS regex: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

You just need to use .* to match 0 or more characters.

You may want .*? to match non-greedily (as in e.g. .*?345 stop at the first instance of '345', not the last). `

like image 24
Beth Crane Avatar answered Sep 09 '25 02:09

Beth Crane