Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Create Custom Regex

Status
Not open for further replies.

BrianAtWork

Programmer
Apr 12, 2004
148
US
Good morning,

I am writing a perl script that is a wrapper for another Unix command. I want to pass my perl script a regex-style string, and then have the perl script modify that string to pass to the Unix command.

The Unix command uses the percent sign (%) as a wildcard instead of the asterisk (*).

For example:

If I want the Unix command to search for the string "string" or "this%string", then I want my perl script to modify the strings like this: "%string%" or "%this%string%".

Or, if I pass the script "^string" - I want the script to modify it as "string%".

And, "string$" would become "%string"

And, "^string$" would become simply "string".

Now, to accomplish this, I could go about it like this:
Code:
if ($string !~/^\^/) { #doesn't have a ^ at the beginning
  $string="\%$string"; #add the leading %
}
else {
  $string=~s/^\^//; #remove the leading ^
}
if ($string !~/\$$/) { #doesn't have a $ at the end
  $string="$string\%"; #add the trailing %
}
else {
  $string=~s/\$$//; #remove the trailing $
}

I think that looks tacky, and I think there has to be a better way to do it...

There's probably a way to do what I want in 2 simple regular expressions, but I'm not seeing the logic.

Does anyone have an idea?

Thanks in advance!

Brian

Oh, and I'm doing this line as well, to turn * into %.
Code:
string=~s/\*/\%/g;
That way users can use regex style wildcards, and they will automatically be converted to the wildcard the unix command uses.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top