4

I need a javascript regex pattern to test a schema variable, so that it should have either of the following.

  1. It can start with any character followed by "_water_glass" and must not be anything after water_glass like "xxxx_water_glass"

or

  1. It can be just "water_glass" not necessary to have character before water_glass and must not be anything after water_glass.

Could anyone help on this please to get the regex pattern.

  • "country_code" can mean a lot of things. Are you talking about [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) codes? If so, the 2 digit ones? The 3 digit ones? Why are you using regex and not just a list? **Have you tried anything yourself or are you expecting others to do your work for free?** If so you may [want to hire a freelancer](http://www.freelancer.com). – h2ooooooo Mar 17 '15 at 15:38
  • I mean exact word "country_code" and not 3 or 2 digit code. since its confusing i replaced it like "water_glass" now. – muthukumar murugesan Mar 17 '15 at 15:40
  • So is your actual question "how to match a word ending with a specific pattern?" Look up the `$` anchor in regex. – h2ooooooo Mar 17 '15 at 15:40

2 Answers2

0

Try this simply /^.*_?\_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

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

Here you are:

^(?:.+_|)water_glass$

Details:

  • ^- start of string
  • (?:.+_|) - an optional 1+ chars other than line break chars, as many as possible, up to the last _ including it
  • water_glass - a water_glass substring
  • $ - end of string.

See this regex demo and a demo code below:

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.
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563