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!

Using index to find alpabetic characters in string

Status
Not open for further replies.

dabits

Programmer
Apr 28, 2000
18
US
Hello! I'm trying to extract the numeric digits from a string which may contain both numeric and alpha characters. For example, <br><br>$wd = '16TH';<br>$tmp = index($wd, /[A-Z]/); # this doesn't work?<br>if ($tmp != -1){<br>&nbsp;&nbsp;&nbsp;&nbsp;$wd = substr($wd,0,$tmp);<br>}<br>but this does!<br>$wd =~ m/[A-Z]/g;<br>$t1 = pos $wd;<br>if ($t1 &gt; 0){<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$wd = $`;<br>}<br>I'm just wondering if regular expressions don't work for index. I know they work for split. What I don't like about the example that does work, is that if the string doesn't contain any alpha characters, $t1 is undefined? What am I missing here?<br>Thanks <br><br>Dabits
 
here's a regex approach<br><b><br>#!/usr/local/bin/perl<br>$string = 'a1b2c3d4e5f6g7';<br>while ($string=~ /\d/g)<br>&nbsp;&nbsp;&nbsp;&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;$number = $&;&nbsp;&nbsp;&nbsp;&nbsp;</b># '$&' catches the matched chars<b><br>&nbsp;&nbsp;&nbsp;&nbsp;print &quot;Found $number\n&quot;;<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br></b><br><br>The above code should print.....<br>Found 1<br>Found 2<br>Found 3<br>Found 4<br>Found 5<br>Found 6<br>Found 7 <br><br><br><br>'Hope this helps.
 
Thanks..<br><br>The regex code does also work. I was just wondering about index.<br><br>Dabits<br><br>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top