Javascript regex pattern for _water_glass

I need a javascript regex pattern to check for a schema variable so that it has one of the following values.

  • It can start with any character followed by "_water_glass" and should not be anything after water_glass, for example, "xxxx_water_glass"

or

  1. It can be just "water_glass", it is not necessary to have a character before water_glass and there should be nothing after water_glass.

Can anyone help with this please to get a regex pattern.

+4
source share
2 answers

Just try /^.*_?\_water_glass/

    var re = /^.*_?_water_glass/mg; 
var str = 'horse.mp3_country_code\n4343434_country_code\n_country_code';
var m;

while ((m = re.exec(str)) != null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}

DEMO https://regex101.com/r/gB9zL7/2

0

:

^(?:.+_|)water_glass$

  • ^ -
  • (?:.+_|) - 1+, , , _,
  • water_glass - water_glass
  • $ - .

- regex - :

var re = /^(?:.+_|)water_glass$/gm; 
var str = 'xxxx_water_glass\nwater_glass';
var m;

while ((m = re.exec(str)) != null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}
0

All Articles