0

Let's say I have a string containing a filename that includes width and height.. eg.

"en/text/org-affiliate-250x450.en.gif"

how can I get only the "250" contained by '-' and 'x' and then the "450" containd by 'x' and '.' using regex?

I tried following this answer but with no luck. Regular Expression to find a string included between two characters while EXCLUDING the delimiters

2
  • 2
    Please show your effort. Commented Aug 13, 2018 at 11:29
  • @Utkanos I tried following this stackoverflow.com/questions/1454913/… but with no luck. Commented Aug 13, 2018 at 11:34

3 Answers 3

3

If you are using R then you can try following solution

txt = "en/text/org-affiliate-250x450.en.gif"
x <- gregexpr("[0-9]+", txt) 
x2 <- as.numeric(unlist(regmatches(txt, x)))
Sign up to request clarification or add additional context in comments.

Comments

1

Use a lookbehind and a lookahead:

(?<=-|x)\d+(?=x|\.)
  • (?<=-|x) Lookbehind for either a - or a x.
  • \d+ Match digits.
  • (?=x|\.) Lookahead for either a x or a ..

Try the regex here.

1 Comment

worked like a charm... thanks for the explanation too.
1

Use the regex -(\d)+x(\d+)\.:

var str = 'en/text/org-affiliate-250x450.en.gif';
var numbers = /-(\d+)x(\d+)\./.exec(str);
numbers = [parseInt(numbers[1]), parseInt(numbers[2])];
console.log(numbers);

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.