0

Let's say I have the following text :

foo bar baz <!-- USERNAME --> <!-- ACCESS_KEY --> baz bar foo

<!--:USERNAME-->

<!-- eueuteh -->

 -DarchetypeVersion=<!-- java-version --> -UserName=<!-- :USERNAME --> -DsauceAccessKey=<!-- ACCESS_KEY --> 

What I want to do is replace <!-- USERNAME --> with some other text. Unfortunately the regex I've created doesn't actually work as intended, and for example replaces the whole <!-- java-version --> -UserName=<!-- :USERNAME --> expression. The first two occurences are replaced properly. Where is the mistake ?

Here's what I've got, testing in javascript console :

var re = new RegExp('(<!--)(.)*(USERNAME)(.)?(-->)');
sasklacz
  • 3,610
  • 10
  • 39
  • 58
  • The problem is with your `(.)*`, that means: match with anything, 0 or more times and it matches with `java-version --> -UserName= – Beterraba Jan 13 '14 at 23:36
  • possible duplicate of [how to make Regular expression into non-greedy?](http://stackoverflow.com/questions/2824302/how-to-make-regular-expression-into-non-greedy) – Ed Heal Jan 13 '14 at 23:37
  • Is this what you're trying to do? http://regex101.com/r/lI8cV8 – Vasili Syrakis Jan 13 '14 at 23:40
  • @VasiliSyrakis please post you're comment as an answer, as right now it's the only one actually working :) thanks ! – sasklacz Jan 13 '14 at 23:53

2 Answers2

4

The correct expression appears to be

/<!--(.(?!-->))*USERNAME.*?-->/g
georg
  • 211,518
  • 52
  • 313
  • 390
1

I use the below technique with things like HTML, XML and similar, (even though it is bad practice when it comes to nested content)

Regex

(<[^>]*)(USERNAME)([^>]*>)


Demo

http://regex101.com/r/lI8cV8

Vasili Syrakis
  • 9,321
  • 1
  • 39
  • 56