TheTechGuy
TheTechGuy

Reputation: 17364

Regex : replace spaces in a file but only target a particular tag (href)

I want to change spaces in the file but only within href=" " tag. The remaining file should not be affected. Is there a way to do it directly in regex, lets say Visual Studio studio, or Sublime or any other editor of your choice

<li><a target="_blank" href="/img/closed-sales/Anderson Ocn Club
2010.pdf" rel="noopener noreferrer">Anderson Ocean Club 2010</a></li>
<li><a target="_blank" href="/img/closed-sales/Anderson ceanClub 2011.pdf" rel="noopener noreferrer">Anderson</a></li>

I have tried href="/.*" which basically matches href="" but I need to replaced spaces and other characters such as @ sign in it. Fiddle

Upvotes: 0

Views: 62

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627087

In Notepad++ or SublimeText, you may leverage the \G construct to match substrings starting from the end of the preceding match thus limiting search and replace to a specific text portion between different delimiters. In your case, the attribute values are enclosed with ", so you may use

(?:\G(?!^)|href="/)[^\s"]*\K\s

and replace with any char(s) you need. If the \K is not supported use

(\G(?!^)|href="/)([^\s"]*)\s

and replace with $1$2[some new text]. The difference between this and the previous patterns is that the text matched with (\G(?!^)|href="/) and ([^\s"]*) is also captured into a group, and the $1 and $2 are corresponding placeholders (numbered replacement backreferences) that refer to the texts captured with those capturing groups.

In Visual Studio, you may use (?<=href="/[^"]*?)\s instead.

See this regex demo.

Details

  • (?:\G(?!^)|href="/) - start of the preceding match or href="/ substring
  • [^\s"]* - 0 or more chars other than " and whitespace
  • \K - match reset operator that removes all text matched so far from the match buffer
  • \s - a whitespace char.

Sublime Text 3 (Windows):

enter image description here

Notepad++:

enter image description here

Visual Studio:

enter image description here

Upvotes: 1

Related Questions