I try-I try, I just can’t make friends with regular expressions:

var str = "ONE=lorem-one-1; TWO=lorem-two-2; THREE=loremthree" 

you need to pull out TWO=lorem-two-2 , and the necessary part can be either in front, in the middle or at the end, the text also has exactly this format ( текст_или_цифры-текст_или_цифры-цифры ) .. preferably I would like to pull it out in groups .. текст_или_цифры-текст_или_цифры-цифры this:

str.match('TWO=(\w\d)-(\w\d)-(\d);?')

but all without success

  • you describe more precisely what line you need to get and from what. but it is not clear what you want to get. - user208916
  • > you need to pull out TWO = lorem-two-2 - cmd
  • Method String.prototype.split() does not solve your problem? It will split your string into an array with three elements, if passed as an argument ; (with a space). Then you can simply refer to the second element of the array or search through each element in search of the necessary one. - neluzhin
  • @terron here, in 90% of cases, you can do without regulars, so you need to describe in detail what you need - user208916

1 answer 1

  1. The match method takes a regular expression as a parameter.
  2. In the above expression, you need to specify that there may be several numbers or letters, for this you can use +

The result is:

 var str = "ONE=lorem-one-1; TWO=lorem-two-2; THREE=loremthree"; console.log(str.match(/TWO=([\w\d]+)-([\w\d]+)-(\d+);?/)); var str2 = "ONE=lorem-one-1; THREE=loremthree; TWO=lorem-two-2"; console.log(str2.match(/TWO=([\w\d]+)-([\w\d]+)-(\d+);?/)); var str3 = "TWO=lorem-two-2; ONE=lorem-one-1; THREE=loremthree"; console.log(str3.match(/TWO=([\w\d]+)-([\w\d]+)-(\d+);?/)); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

As @Wiktor Stribiżew suggests , the regular expression can be slightly simplified, since \d is included in \w . The result is:

 var str = "ONE=lorem-one-1; TWO=lorem1-two-2; THREE=loremthree"; console.log(str.match(/TWO=(\w+)-(\w+)-(\d+);?/)); var str2 = "ONE=lorem-one-1; THREE=loremthree; TWO=lorem2-two-2"; console.log(str2.match(/TWO=(\w+)-(\w+)-(\d+);?/)); var str3 = "TWO=lorem3-two-2; ONE=lorem-one-1; THREE=loremthree"; console.log(str3.match(/TWO=(\w+)-(\w+)-(\d+);?/)); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

  • one
    NB: [\w\d] = \w - Wiktor Stribiżew
  • @ WiktorStribiżew, are the numbers in \w ? :) - Grundy
  • @ WiktorStribiżew, updated the answer. - Grundy
  • one
    Yes, \w finds numbers, letters, and underscores. In JS, letters and numbers are only from the ASCII character set. - Wiktor Stribiżew