0

I have a text that has following strings:

Lorem ipsum - sit
Dolor sit - consectetur adipiscing elit
Adipiscing elit
Integer egestas - congue
Egestas quam

I need to get this:

Lorem ipsum 2017 - sit
Dolor sit 2017 - consectetur adipiscing elit
Adipiscing elit 2017
Integer egestas 2017 - congue
Egestas quam 2017

I try to do it use regular expression for each string:

name.replace(/([a-zA-Z\s].*)([-]?)/, '$1 '  + 2017 + ' $2') 

but get year at the end of each string.

Lorem ipsum - sit 2017 
Dolor sit - consectetur adipiscing elit 2017 
Adipiscing elit 2017 
Integer egestas - congue 2017 
Egestas quam 2017 

3 Answers3

0

const textOne = 'text one -one';
const textTwo = 'text two two';
console.log(textOne.replace(/([a-zA-Z\s]*)([-]?)/, '$1'  + 2017 + ' $2'));
console.log(textTwo.replace(/([a-zA-Z\s]*)([-]?)/, '$1 '  + 2017 + ' $2'));

I think this will do it.

Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26
  • 1
    Code dumps are not *useful* answers. Say *what* you did, and *why*. Also strongly recommend using the OP's supplied input data, not data you've made up yourself, to make it easier to see that it's correct. – T.J. Crowder Oct 22 '19 at 08:30
0

Assuming you're doing this line-by-line (since there's no g on the regular expression), then as Federico klez Culloca said, remove the . in .*. Also note that '$1 ' + 2017 + ' $2' is more directly written simply '$1 2017 $2':

name.replace(/([a-zA-Z\s]*)([-]?)/, '$1 2017 $2')
// No . here ------------^

Live Example:

const text = `Lorem ipsum - sit
Dolor sit - consectetur adipiscing elit
Adipiscing elit
Integer egestas - congue
Egestas quam`;

console.log(text.split(/\r?\n/).map(name =>
  name.replace(/([a-zA-Z\s]*)([-]?)/, '$1 2017 $2')
).join("\n"));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Here it is with some negative lookahead groups....

enter image description here

const regex = /^((?:(?! - ).)+)/gm;
const str = `Lorem ipsum - sit
Dolor sit - consectetur adipiscing elit
Adipiscing elit
Integer egestas - congue
Egestas quam`;
const subst = `$1 2017`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);
Patrick Ferreira
  • 1,983
  • 1
  • 15
  • 31
  • 1
    `(?:.(?!- ))+` is a corrupt [tempered greedy token](https://stackoverflow.com/questions/30900794/tempered-greedy-token-what-is-different-about-placing-the-dot-before-the-negat), use `(?:(?!- ).)+` instead. The dot must be preceded with the negative lookahead. – Wiktor Stribiżew Oct 22 '19 at 09:02
  • 1
    The fix is `/^(?:(?!- ).)+/`. The dot is not tempered when the lookahead is after it. Even if it works in this case, it is bad practice and should not be used. You do not need a capturing group at all since there is a `$&` backreference. – Wiktor Stribiżew Oct 22 '19 at 09:07