itdoesntwork
itdoesntwork

Reputation: 1891

Regex match string between two characters

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

Upvotes: 0

Views: 934

Answers (3)

Chayim Friedman
Chayim Friedman

Reputation: 71555

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);

Upvotes: 1

Paolo
Paolo

Reputation: 26265

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.

Upvotes: 1

girijesh96
girijesh96

Reputation: 455

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)))

Upvotes: 3

Related Questions