examples <- c( "abc foo", "abc foo 17", "0 abc defg foo 5 121", "abc 12 foo defg 11" )
res <- gsub(".*?foo\\D*(\\d+).*|.*", "\\1", examples)
res[nchar(res)==0] <- NA
## => [1] NA "17" "5" "11"
ZXhhbXBsZXMgPC0gYyggImFiYyBmb28iLCAiYWJjIGZvbyAxNyIsICIwIGFiYyBkZWZnIGZvbyA1IDEyMSIsICJhYmMgMTIgZm9vIGRlZmcgMTEiICkKcmVzIDwtIGdzdWIoIi4qP2Zvb1xcRCooXFxkKykuKnwuKiIsICJcXDEiLCBleGFtcGxlcykKcmVzW25jaGFyKHJlcyk9PTBdIDwtIE5BCiMjID0+IFsxXSBOQSAgICIxNyIgIjUiICAiMTEiCg==