0

I would like to match all characters in a string except for the #*# pattern. The regex I have below works for cases such as match1 below, but it will also match #'s or 's that are not in the ## pattern as seen in match2 below and fail because of that. How can I fix the below regex to match #*# if they appear together?

var string1 = 'Hello#*#World#*#Some other string#*#false'
var string2 = 'Hello#*#World#*#Some #other #string#*#false'
// This would match
var match1 = string1.match(/^([^#*#]+)#\*#([^#*#]+)#\*#([^#*#]+)#\*#([^#*#]+)$/);  
// This would no longer match since it matches other #'s that are not in a #*# pattern
var match2 = string2.match(/^([^#*#]+)#\*#([^#*#]+)#\*#([^#*#]+)#\*#([^#*#]+)$/);

Also the match should match the whole words between the pattern. So for match1 it would be

[ 'Hello#*#World#*#Some other string#*#false',
  'Hello',
  'World',
  'Some other string',
  'false',
  index: 0,
  input: 'Hello#*#World#*#Some other string#*#false',
  groups: undefined ]
Adrian
  • 45
  • 1
  • 6

1 Answers1

1

You can try this.

var string1 = 'Hello#*#World#*#Some other string#*#false'
var string2 = 'Hello#*#World#*#Some #other #string#*#false'
// This would match
var match1 = string1.match(/[^(#\*#)]+/g);  

var match2 = string2.match(/[^(#\*#)]+/g);

console.log(match1);
console.log(match2);
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • I updated my question because I meant to ask about matching the full words in between the #*# instead of each unique character. See the example match in my question – Adrian Dec 05 '18 at 19:48
  • @Adrian updated answer. if it help you can select it as correct answer :p anyways happy to help :) – Code Maniac Dec 06 '18 at 05:16
  • Thank you this is perfect! I had something similar at one point but without the global modifier – Adrian Dec 06 '18 at 14:41