简体   繁体   中英

Regex: extract before, after character

given the following string

stringData= "goal01=4 goal02=2 goal06=3 goal09=1 goal12=5 goal13=2 goal14=4 planet=52 people=48 Inclusion=4 HealthWellness=2 SustainableInfrastructure=4 ResponsibleConsumption=9 Environment=2" 

I need a regex to parse the following two variants

stringColumns = stringData(regex that //fetch before '=' and add ',' to string i.e goal01,goal02,planet etc..) 
stringValues= stringData(regex that //fetch after '=' and same as above 4,2,3,52, etc..) 

as I need them split in order to construct a sql insert statement such as

sqlSyntax = "INSERT INTO [table] ("'+stringColumns+'") VALUES ("'+stringValues+'")"

I tried ^([^=])+ and it only matched the first goal01 what do I need to fetch all the remainings?

https://regex101.com/r/QZgfPh/1

You do not need regex. Simply split with spaces then with equal signs and pull out the necessary characters:

 var stringData = "goal01=4 goal02=2 goal06=3 goal09=1 goal12=5 goal13=2 goal14=4 planet=52 people=48 Inclusion=4 HealthWellness=2 SustainableInfrastructure=4 ResponsibleConsumption=9 Environment=2"; var dataArray = stringData.split(" ") var stringColumns = dataArray.map(item => item.split("=")[0]).join(","); var stringValues = dataArray.map(item => item.split("=")[1]).join(","); console.log(stringColumns); console.log(stringValues);

Here is the ES5 equivalent, in case you cannot use ES6 arrow functions:

 var stringData = "goal01=4 goal02=2 goal06=3 goal09=1 goal12=5 goal13=2 goal14=4 planet=52 people=48 Inclusion=4 HealthWellness=2 SustainableInfrastructure=4 ResponsibleConsumption=9 Environment=2"; var dataArray = stringData.split(" ") var stringColumns = dataArray.map(function(item) { return item.split("=")[0]; }).join(","); var stringValues = dataArray.map(function(item) { return item.split("=")[1]; }).join(",");; console.log(stringColumns); console.log(stringValues);

However, if you explicitly want to do it using regex, you can do this:

 var stringData = "goal01=4 goal02=2 goal06=3 goal09=1 goal12=5 goal13=2 goal14=4 planet=52 people=48 Inclusion=4 HealthWellness=2 SustainableInfrastructure=4 ResponsibleConsumption=9 Environment=2"; var stringColumns = stringData.match(/[A-Za-z0-9]+(?==)/g).join(","); var stringValues = stringData.match(/(?<==)[0-9]+/g).join(","); console.log(stringColumns); console.log(stringValues);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM