pete
pete

Reputation: 21

regular expression to extract middle section of string

What could be the regex to extract 58392 from this example.

the number between the colon and hash would be variable length

sip:58392#[email protected]

I tried conbinations of like this but no luck sip:(.*?)#/\1/

Upvotes: 2

Views: 19353

Answers (4)

hek2mgl
hek2mgl

Reputation: 157967

here is a PHP example:

<?php

$string = 'sip:58392#[email protected]';
$pattern = '/^sip:([0-9]+)#/';
preg_match($pattern, $string, $matches);
echo "the number is : ", $matches[1];

Upvotes: 1

SaidbakR
SaidbakR

Reputation: 13544

The following will match sip:58392# and then by any split string method, I think that you are able to remove sip: and #.

sip:.*?\#

Upvotes: 0

Karl Barker
Karl Barker

Reputation: 11341

In Python 2.7.3:

>>> import re
>>> r = r"sip:(.*?)#"
>>> s = "sip:58392#[email protected]"
>>> re.findall(r,s)
['58392']

...it works.

I don't get what the /\1/ at the end of your regex is for - probably something for the specific flavour of regex you're using, but I suspect that's the problem.

Upvotes: 0

John Woo
John Woo

Reputation: 263723

try this expression,

(?<=:).*?(?=#)

See Lookahead and Lookbehind Zero-Width Assertions

Upvotes: 9

Related Questions