Page 1 of 1

Looping through with regexreplace

Posted: 23 Nov 2009 00:07
by zer0
I'm in a bit of a bind and I'm wondering if another forum user who's quite into scripting can help me out. I'm sure it's something obvious, but I can't think what it is. Basically, this script is meant to loop through selected items and 'regexreplace' each file's contents. Here's what I came up with

Code: Select all

"Text Loop"
   $filelist = getinfo('SelectedItemsPathNames', '|');
   $p = strpos($filelist, '|');
   while ($p >= 0)
   {
      $filelist = substr($filelist, $p + 1);
      regexreplace $data, readfile("<curitem>"), "\n", "<crlf>"; 
      writefile("<curitempath>\<curbase>.nfo", "$data");
   } 
However, running this script on selected items shows an error message that says that "File missing!" on line "regexreplace $data, readfile("<curitem>"), "\n", "<crlf>";" I'd appreciate if someone can enlighten me why that is, thank you :)

Re: Looping through with regexreplace

Posted: 23 Nov 2009 01:06
by Muroph
i don't think that script will work for several reasons.
mainly because "$p" will always be >=0 if you have smth selected, so "while" will loop infinitely.

try this:

Code: Select all

"Text Loop"
	$filelist = getinfo('SelectedItemsPathNames', '|');
	$count=1;
	while(1){
		$file=gettoken($filelist,$count,"|");
		if("$file"==""){break;}
		$data=regexreplace(readfile("$file"), "\n", "<crlf>");
		$base=regexreplace($file,"^(.+)\..+?$","$1");
		writefile("$base.nfo", "$data");
		$count++;}
	status "Done!",,ready;

Re: Looping through with regexreplace

Posted: 23 Nov 2009 10:25
by zer0
Thank you Muroph! That script works just right. I see where I went wrong with the looping and using 'regexreplace' not quite right 8)

Re: Looping through with regexreplace

Posted: 24 Nov 2009 13:03
by zer0
On a slightly related note of using 'regexreplace'. I am struggling to be able to nail down a pattern to match any text inside square brackets and inside quotation marks. For example, for [anytext], using [\[.*\]] doesn't isolate anytext for replacement with my chosen string. Same story with quoted strings. I'd appreciate any assistance, because this one is proving to be a tough nut to crack 8)

Re: Looping through with regexreplace

Posted: 24 Nov 2009 14:16
by Muroph
not tested, but \[.*\] and ".*" might work.
they will also match the brackets and quotes, so you'll have to include those in the replacement string.
for example:
string: foo[anytext]bar
regex: \[.*\]
replacement: [newtext]
new string: foo[newtext]bar

if you want to match only the text inside the brackets then you'll need to use lookahead and lookbehind.
i don't think xy's regex engine supports them, tho.

Re: Looping through with regexreplace

Posted: 24 Nov 2009 15:51
by zer0
Indeed, your RegEx pattern works fine, thank you. It appears I was overly enthusiastic with the square brackets when defining a range :oops: