0
2f34435-something.jpg
4t44234-something.jpg
5465g67-something.jpg

says I have 3 string above, without using split, how can I do regex to get the value before dash? the length of strings is not consistent though..

2
  • Why don't you want to use split? Commented Jan 12, 2016 at 3:34
  • You don't need to use regex, use string methods. str.substring(0, str.indexOf('-')); Commented Jan 12, 2016 at 4:18

4 Answers 4

2

One option would be to match one or more non-dash characters at the beginning of the string:

^[^-]+
  • ^ - Anchor that denotes the beginning of the string
  • [^-] - Character set to match all characters that are not dashes.
  • + - One or more occurrences of non-dash characters.

For instance:

'2f34435-something.jpg'.match(/^[^-]+/);
// ["2f34435"]

With the .split() method, you would just need to retrieve the first match:

'2f34435-something.jpg'.split('-')[0];
// "2f34435"
Sign up to request clarification or add additional context in comments.

Comments

1

you can use...

/^(.+?)-/gm

which will capture all 3 ( or as many as you have )

You can see it in action here https://regex101.com/r/gD5sU2/2

This will also handle if you get - in the rest of the filename...

such as :-

2f34435-something-else.jpg
4t44234-something.jpg
5465g67-something.jpg

5 Comments

what does the plus sign do here? and do we need bracket?
. is any character and + is 1 or more
the brackets indicate the part you want to capture
I found the ^ is not required.
oh, it isn't in the examples, it was supposed to handle if there was another - in the filename, but that doesn't quite work.... I'll update my answer
0

([a-z0-9]+)-[a-z0-9]+.jpg matches each of those strings and the string returned from the first group will match the text before the dash.

1 Comment

This will break if there's a second dash.
0

Use look ahead for to do it

/^.+?(?=-)/gm

https://regex101.com/r/mW5bO7/2

Comments

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.