Unix Regular Expression is not working

Help with writing and running scripts

Unix Regular Expression is not working

Postby Askedal » Fri Sep 07, 2007 8:17 am

Hi,

i try to find some text based on a Unix RegEx:

Code: Select all
UltraEdit.activeDocument.top();
UltraEdit.unixReOn();
UltraEdit.activeDocument.findReplace.regExp = true;
UltraEdit.activeDocument.findReplace.replaceAll = true;

var regexpFind = "\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\.\d\d ";


UltraEdit.activeDocument.findReplace.find(regexpFind);
if (UltraEdit.activeDocument.isFound()){

 UltraEdit.outputWindow.write("Found")

} else {

 UltraEdit.outputWindow.write("Not Found")

}


The Text to search in is:
//2007-07-20 18:30:27.74 server SQL Server is starting at priority class 'normal'(3 CPUs detected).

The code should find the 2007-07-20 18:30:27.74 at the beginning. When i use the GUI Search & Replace and search for the RegEx it finds the string.
If i change the RegEx to "\d" only to find a single digit, it finds the "d" in "detected".

Thanks in advance

Askedal
User avatar
Askedal
Newbie
 
Posts: 2
Joined: Thu Jan 05, 2006 12:00 am

Re: Unix Regular Expression is not working

Postby jorrasdk » Fri Sep 07, 2007 9:25 am

Hi Askedal

This is a classic. In Javascript backslash is an escape character for special control characters and such. So if you want to use backslash as a real "normal" backslash you have to escape this using backslash by doubling all backslashes. I know this sounds confusing but just change the assignment for regexpFind variable to:

Code: Select all
var regexpFind = "\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d\\.\\d\\d ";


and your script will work.
User avatar
jorrasdk
Master
Master
 
Posts: 275
Joined: Mon Mar 19, 2007 11:00 pm
Location: Denmark

Re: Unix Regular Expression is not working

Postby jorrasdk » Fri Sep 07, 2007 9:49 am

to follow up on my own post: Escaping backslashes in regExp's in javascript makes the regExp's even more difficult to read (and cut and paste from other applications), so you can use the regExp object type instead of string object type and add a prototype function shown below:

Code: Select all
UltraEdit.activeDocument.top();
UltraEdit.unixReOn();
UltraEdit.activeDocument.findReplace.regExp = true;
UltraEdit.activeDocument.findReplace.replaceAll = true;

var regexpFind = new RegExp(/\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\.\d\d /); /* paste or edit regExp between / / */

RegExp.prototype.toUEregexpString = function() { return this.toString().replace(/^\/|\/$/g, ""); }; /* remove starting and ending / as UE does not recognize these for regexp */

UltraEdit.activeDocument.findReplace.find(regexpFind.toUEregexpString()); /* call new prototype function to convert to String */
if (UltraEdit.activeDocument.isFound()){
  UltraEdit.outputWindow.write("Found");
} else {
    UltraEdit.outputWindow.write("Not Found");
}
User avatar
jorrasdk
Master
Master
 
Posts: 275
Joined: Mon Mar 19, 2007 11:00 pm
Location: Denmark


Return to Scripts