Regular expression help

Using rSymPy to solve the system of equations, I got the x and y values ​​that solve the system in a character string, for example this:

"[(1.33738072607023, 27.9489435205271)]" 

How to assign these 2 values ​​to x, y variables?

+4
source share
3 answers

To break a line, you can use:

 vect <- as.numeric(strsplit(gsub("[^[:digit:]\\. \\s]","",x)," ")) x <- vect[1] y <- vect[2] 

This removes everything that is not space, point, or number. strsplit breaks the line left in the vector. See Also related help files.

Assignment can be done in a loop or using the Gavin function. I would call them.

 names(vect) <-c("x","y") vect["x"] x 1.337381 

For large datasets, I like to keep things together to avoid overloading the workspace with names.

+4
source

Here are a few steps that will do what you want to do. This is not to say that this is the most effective or elegant solution ...

 string <- "[(1.33738072607023, 27.9489435205271)]" string <- gsub("[^[:digit:]\\. \\s]", "", string) splt <- strsplit(string, " ")[[1]] names(splt) <- c("x","y") FOO <- function(name, strings) { assign(name, as.numeric(strings[name]), globalenv()) invisible() } lapply(c("x","y"), FOO, strings = splt) 

The last line will return:

 > lapply(c("x","y"), FOO, strings = splt) [[1]] NULL [[2]] NULL 

And we have x and y assigned in the global environment

 > x [1] 1.337381 > y [1] 27.94894 
+2
source

strapply in the gsubfn package makes it pretty easy to extract numbers from strings using only a relatively simple regular expression. Here s is the input string, and v is a numerical vector with two numbers:

 library(gsubfn) v <- strapply(s, "[0-9.]+", as.numeric)[[1]] x <- v[1] y <- v[2] 
+2
source

Source: https://habr.com/ru/post/1335828/


All Articles