0

my string can be

new-york-10036

or

chicago-55036

the desired result is

new-york
chicago

and i basically want to remove all the string that come after the first dash - followed by a number

seems easy but i don't know how

4
  • 2
    Have you tried starting with some attempts or pseudo code? Commented Mar 4, 2016 at 0:23
  • This one should be enough (.*)-\d+ regex101.com/r/mY6fW3/2 Commented Mar 4, 2016 at 0:31
  • 1
    You already have a good start with this: "i basically want to remove all the string that come after the first dash - followed by a number" now you can try to put it into a more general pseudo regex, like: [Anything]-number(s), which you then can try to translate step by step into a regex like: (.*)-\d+ Commented Mar 4, 2016 at 0:58
  • pretty sure this would work with preg_match_all: /([a-zA-Z\-]+)\-[0-9]+/g Commented Mar 4, 2016 at 1:00

1 Answer 1

3

You can use Negative Lookahead, like so:

(.+)(?=\-\d)

The regex reads: "get me everything that is not followed by exactly one dash and exactly one number after that".

Given the input new-york-10036 the regex is going to capture only new-york. In PHP you can get the matched string with:

$string = 'new-york-10036';

$regex = '/(.+)(?=\-\d)/';

preg_match($regex, $string, $return);

echo $return[0] . "\n";

It outputs new-york.

See the regex working here.

Sign up to request clarification or add additional context in comments.

7 Comments

does the "d" stands for number?
@Francesco actually, it's the \d, which stands for "a number between 0 and 9". It's the same as [0-9] and is called a "character class", which you can see here.
@Francesco Yes, \d == [0-9], but you can probably better remember it with digit
@Francesco preg_match !== preg_match_all
my question was about PHP: given the regex, how do i extract the string?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.