Link to home
Start Free TrialLog in
Avatar of m0tSiE
m0tSiE

asked on

Extract part of string (Regex)

Hi,

Can anyone show me how i can extract the following using regex?

My string is "TITLE PART 1/13"

I'm looking to extract "PART 1/13".

This wont always be at the end of the string as the string will change, for example it could show as "TITLE PART 1/13 MORE TEXT"

Regards,

Paul
Avatar of ygoutham
ygoutham
Flag of India image

echo "TITLE PART 1/13 MORE TEXT some random text that comes here" | cut -d" " -f2-100

that should be all
Avatar of m0tSiE
m0tSiE

ASKER

It shows the error:

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';' in regex.php  on line 3
sorry the above was a linux command, did not see the php portion of it


$searchstring = "TITLE PART 1/13 MORE TEXT some random text that comes here";

$searchpos = strpos($searchstring, " ");

$resultstring = substr($searchstring, $searchpos+1, strlen($searchstring) );

echo "$resultstring";
Avatar of m0tSiE

ASKER

Thanks, I tried it, but it doesn't work. By just searching for the first space as the title wont always be 1 word and i'm only after "Part x/xx", not the text after that.
would the word "PART" be a constant then we can use that to find the string

$searchstring = "TITLE PART 1/13 MORE TEXT some random text that comes here";

$searchpos = strpos($searchstring, "PART");

$resultstring = substr($searchstring, $searchpos, strlen($searchstring) );

echo "$resultstring";

SOLUTION
Avatar of ygoutham
ygoutham
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of Shahan Ayyub
Shahan Ayyub
Flag of Pakistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Paul, you can use this Regex, if your denominator length > 2 digits.

PART \d\/\d+

otherwise the previousone would be enough, i.e.,

PART \d\/\d{2}


-Shahan
FYI: I used +'s on both sides to allow for the match "PART 24/325"
Theodorejsalvo's solution looks perfect to me.
Works fine in Python, take in mind that the regular expression is:

(TITLE\s+PART\s+\d+/\d+).*

>>> import re
>>> s = "TITLE PART 1/13 OTHER TEXT"
>>> regex = re.compile( r"(TITLE\s+PART\s+\d+/\d+).*", re.I )
>>> match = regex.search( s )
>>> print match.group( 1 )
TITLE PART 1/13
Avatar of m0tSiE

ASKER

Thanks All :)