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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using regular expressions to extract "adjacent" substrings

Status
Not open for further replies.

MaxCarp

Programmer
Aug 16, 2011
5
US
Suppose I have strings of the form:
xxxxxxxxxxZYYYxxxxxx

where x can be any character, Z is some specific character, and Y is a certain character type (i.e. digits) of arbitrarily length. I want to exploit the fact that substring Y...Y always appears after Z, and write a regular expression that extracts Y.

Thank you in advance!
 
Something like this?

Perl:
$ echo xxxxxxxxxxZYYYxxxxxx xxxxxxxxxxZYYxxxxxx | perl -ne '[COLOR=#0000FF]while[/color] (/\S+Z(Y+)\S+/g) { [COLOR=#FF0000]print[/color] [COLOR=#808080]"$1\n"[/color];}'
YYY
YY

Annihilannic.
[small]tgmlify - code syntax highlighting for your tek-tips posts[/small]
 
Actually, I was looking for a regular expression to extract Y...Y (as many consecutive instances of the variable of type Y following Z as there are).

Would just =~ /\S+Z(Y+)\g
print $1

work (it doesn't in the code).

Thanks, Max
 
That expression has exactly the same result for me when applied to the same test above. To me it sounds like I'm outputting exactly what you're asking for... I'm not sure I understand your requirements clearly? Do you have an example of the input data and what you want to extract from it? Also... where do you want to extract it to?

Annihilannic.
[small]tgmlify - code syntax highlighting for your tek-tips posts[/small]
 
For one thing, I only want to extract the YY..Y part of the string. The regular expression should contain a statement that identifies the variable of type Y by its adjacency to Z, but only returns the Y.
 
Err... yeah... that's pretty much how I understood it... and it's exactly what my example does?

Annihilannic
[small]tgmlify - code syntax highlighting for your tek-tips posts[/small]
 
Perhaps you just wanted this one?
Code:
my$mys='xxxxxxxxxxZ123xxxxxx xxxxxxxxxxZ09xxxxxx';
my@mtc=$mys=~/Z(\d*)/g;
print"@mtc\n";
Replace the star with a '+' if you don't want to capture strings of zero length.

Franco
: Online engineering calculations
: Magnetic brakes for fun rides
: Air bearing pads
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top