簡體   English   中英

正則表達式:在字符之前,之后提取

[英]Regex: extract before, after character

給定以下字符串

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" 

我需要一個正則表達式來解析以下兩個變體

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

因為我需要將它們拆分以構建 sql 插入語句,例如

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

我試過^([^=])+並且它只匹配第一個目標goal01我需要什么來獲取所有剩余部分?

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

您不需要正則表達式。 簡單地用空格分割然后用等號並拉出必要的字符:

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

這是 ES5 等效項,以防您無法使用 ES6 箭頭函數:

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

但是,如果您明確想使用正則表達式來執行此操作,則可以執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM