Saturday, October 01, 2005

 

Regex Tester

It occurred to me that constructing a script that helps test Regex commands would be a good idea, so I came up initially with this script (which uses all three of the methods and functions in the previous blog entry):
if ((app.documents.length != 0) && (app.selection.length != 0)) {
 var myRange = app.selection[0];
 if (myRange.isText()) {
  // if selection is only an insertion point, process parent text range
  if (myRange.constructor.name == "InsertionPoint") {
   myRange = getParentTextFlow(myRange);
  }
  
  // Invite user to type regular expression
  app.activate();
  var myREtext = prompt("Type your regular expresion","");
  if (myREtext == null) { errorExit() }
  myRE = new RegExp(myREtext);
  var myTest = myRE.exec(myRange.contents);
  app.activate();
  alert(myRE + " finds:\n" + myTest[1]);
 }
} else {
 errorExit("Please select some text and try again");
}
To use this script, select some text in an InDesign document (or click in a story or table cell) and run the script. It prompts you for a Regex string and displays the result in an alert. However, even as I sit here describing this version, I see a couple of problems.

First, the script focuses on the first matched substring of text. But what if you're not interested in substrings? Well, my "solution" to that is a bit clunky: surround your whole search string in parentheses.

Second, although the script looks as though it deals with non-text selections, it actually doesn't. The "else" statement is only triggered if there is either no document open or no selection.

Let's try to fix both of these by (a) being a bit smarter with the results of the exec() call and (b) by giving the script a better internal structure.
var myErr = "Please select some text and try again";
if ((app.documents.length != 0) && (app.selection.length != 0)) {
 var myRange = app.selection[0];
 if (!myRange.isText()) {
  errorExit(myErr);
 } else {
  // if selection is only an insertion point, process parent text range
  if (myRange.constructor.name == "InsertionPoint") {
   myRange = getParentTextFlow(myRange);
  }
  
  // Invite user to type regular expression
  app.activate();
  var myREtext = prompt("Type your regular expresion","");
  if (myREtext == null) { errorExit() }
  myRE = new RegExp(myREtext);
  var myTest = myRE.exec(myRange.contents);
  var myReport = myRE + " finds:";
  if (myTest == null) {
   myReport = myReport + " no match";
  } else {
   myReport = myReport + "\n" + myTest[0];
   for (var j = 1; myTest.length > j; j++) {
    myReport = myReport + "\n$" + String(j) + " = " + myTest[j];
   }
  }
  app.activate();
  alert(myReport);
 }
} else {
 errorExit(myErr);
}

There, now that's what I call a useful script!

Comments:
I constantly spent my half an hour to read this website's articles or reviews all the time along with a cup of coffee.

my web blog ... software download
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?