Question

I have a string that i would like to extract the first instance of the character/digit mix - ie the first instance of the screen resolution below.

The string to match

scrn <- "  dimensions:    1280x800 pixels (338x211 millimeters)"

And i would like to get either a vector or list with entries c(1280, 800)

I can do this rather awkwardly with

strsplit(sapply(strsplit(scrn, " "), "[", 7),"x", scrn)

where i knew the 7 by reviewing the strsplit output.

But i am assuming there is a neat regular expressions way to do this

My attempt fwiw (which i would then need to split a couple of times)

gsub("[[:alpha:]]{2,}|(\\:)*(\\s) ", "", scrn)
Was it helpful?

Solution 2

Following @zx81 hint of (\\d+)x(\\d+) this gets it done fairly neatly

scrn <- "  dimensions:    1280x800 pixels (338x211 millimeters)"
g <- regexec("(\\d+)x(\\d+)",  scrn)
unlist(regmatches( scrn, g ))[-1]

OTHER TIPS

Is this what you mean?

sub('scrn\\s*<-\\s*"\\s*dimensions:\\s*(\\d+)x(\\d+)', "c(\\1,\\2)", subject, perl=TRUE);

Output:

c(1280,800)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top