Sublime Forum

Help with programmatic search replace

#1

Hi all,

I’ve made a simple plugin that updates meta data in an HTML page on command. The problem is when a closing slash is included in the tag, the search doesn’t match it. When I copy and paste the regex into the editor directly, it matches perfectly. I don’t know if this is a regex problem (with the trailing slash being interpreted as a segmentation character), if this is a view.find() problem, both, or something else entirely. The relevant part of my code is below:

import sublime, sublime_plugin, os

class UpdatemetaCommand(sublime_plugin.TextCommand):
	def run(self, edit):

# Get the current user environment variable. Windows uses 'USERNAME', while Mac uses 'USER'
		user = os.environ.get( "USERNAME" )
		if not user:
			user = os.environ.get( "USER" )
		
#Searches and replaces the developer tag; 
#Regex here matches in regular find/replace with regex turned on. 
#In code, it matches:
#<meta name="developer" content="foo">
#but not
#<meta name="developer" content="foo"/>
#or
#<meta name="developer" content="foo" />
		tag = self.view.find('<meta name="developer" content=".^>]*>', sublime.IGNORECASE)
		self.view.replace(edit, tag, '<meta name="developer" content="' + user + '">')

I’ve tried a couple variations of the regex to no avail. The above and below:

<meta name="developer" content=".*

The console gives me an error that seems to be related to the fact that tag is ending up null because view.find() isn’t matching anything.

I’m fairly new to plugin (and Python for that matter) development, so I apologize in advance if this is documented someplace. Any help would be appreciated.

0 Likes

#2

You might want to check, find() takes 3 arguments. The second argument is the “from position”, like 0.

0 Likes

#3

Bah. Thanks for the help. That seemed to have fixed it!

0 Likes