Reputation: 7233
Hi I need a Regex that can actually get any letter that is inserted after "-" dash e.g i have a string that says
"UpTown-R" , "Category-C"
What I get in return is "R" , "C".
Upvotes: 2
Views: 18312
Reputation: 14877
A simple
-(.+)$
Will get everything that it's after the first dash; note that with this string foo-bar-baz
you will match -bar-baz
, and bar-baz
will be in first group.
If you have to match only letters,
-([A-Za-z]+)$
Will suffice. Your result will be in the $1
group.
Alternatively, why don't you substr
your string, starting from the last dash index way to end of the string?
Upvotes: 2
Reputation: 76405
Why would you use slow regex's for this, why not just explode the string on '-'?
$str = 'UpTown-R';
$arr = explode('-',$str);
$letter = $arr[1];
$letterSage = $arr[1][0]; // to be sure you only get 1 character.
This works just as well! Before writing regex's all over the place, think of these wise words: "If your solution consists of more than 3 regular expressions, you're part of the problem"
Upvotes: 1
Reputation: 92986
If is always the last part of the string, you can do this
/[^-]+$/
see it here on Regexr
[^-]
is a character class that matches everything that is not a dash
+
quantifier means one or more of the preceding element
$
anchor for the end of the string
Upvotes: 8
Reputation: 91385
How about:
preg_match('/-([a-z])\b/i', $string, $match);
unicode compatibility:
preg_match('/-(\pL)\b/u', $string, $match);
The letter you want is in $match[1]
.
Upvotes: 3
Reputation: 208
Here you are:
(?<=-)(.)
Results are in group 1.
Tested using:
Upvotes: 3
Reputation: 912
try this regex;
/^.*\-(.*)$/
this way you get everything after the dash
Upvotes: 1