TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   Remembering why I hate Regex (http://www.talkphp.com/absolute-beginners/1906-remembering-why-i-hate-regex.html)

RobertK 01-08-2008 09:33 PM

Remembering why I hate Regex
 
Well, I'm trying to do a quick regex match here, and it won't stop choking. The strings are formatted as:
  1. abc
  2. abc123
  3. abc123,1

I am trying to skip the initial text, if any, and find that middle number before the comma. Unfortunately it keeps dying. The center number can reach from 1-3 digits in length.

I've tried patterns based off this:
PHP Code:

  preg_match('/([\d]{1,3}*?)[,]*/'$hash$matches);
  if(
count($matches) === 1) {
    if(
is_numeric($matches[0][0])) {
      
$bits intval($matches[0][0]);
      
$hex $bits 4;
    }
  }
  unset(
$matches); 

However it tells me: "Compilation failed: nothing to repeat at offset 10"

I hope someone around here can remind me how to do it right... *!*

Wildhoney 01-08-2008 09:41 PM

Would the following be OK?

php Code:
$szText = 'abc123,1';
preg_match('~(?P<numbers>[0-9]{1,3})~', $szText, $aMatches);

var_dump((int) $aMatches['numbers']);

RobertK 01-08-2008 09:52 PM

Yeah, thanks. That helps a lot. Found around 2-3 different errors in that section total. Now I'm just working on a switch statement that isn't working.

Salathe 01-09-2008 02:26 PM

You've already got the problem solved but I see no reason to waste time and energy when it's not necessary. Is there any reason why the following would not suffice?

PHP Code:

$hash 'abc123,1';
if (
preg_match('/\d{1,3}/'$hash$matches))
{
    
$bits = (int) $matches[0];
    
$hex  $bits 4;
    unset (
$matches);



RobertK 01-09-2008 02:37 PM

Methinks that would work a bit faster, without the string match. Thanks Salathe. :-)


All times are GMT. The time now is 08:10 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0