[英]Splitting this string using javascript or ruby
我有以下字符串:
Upper and lower ranch milk 125ML (3 * 8)
以及其他1000個格式不同的類似內容。 我想將產品(文本部分),卷( 125ML
)和排序規則( (3 * 8)
)分成單獨的變量。
我嘗試使用excel和matlab來提出一個功能,但是未能達到預期的效果。 我想提出一種聰明的方法,而不是手動篩選每個方法。 所有輸入表示贊賞。
您可以使用正則表達式,例如^(.*)( \\d+ML) +\\((.*)\\)
說明
^(.*)
組1:從頭開始的任何字符
( \\d+ML)
第2組:一個空格,后跟數字和ML的體積
+\\((.*)\\)
第3組:括號中至少有一個空格后的任何內容
應用於樣本字符串
完全匹配的Upper and lower 2 ranch milk 125ML (3 * 8)
第一組: Upper and lower 2 ranch milk
第2組: 125ML
第3組: 3 * 8
JavaScript中的示例代碼段
看控制台
function extractInformation(from) { var re = /^(.*)( \\d+ML) +\\((.*)\\)/; var matches = re.exec(from); if(matches) { return { "title" : matches[1].trim(), "volume": matches[2].trim(), "collation": matches[3].trim(), } } return {}; } console.log(extractInformation("Upper and lower ranch milk 125ML (3 * 8)")); console.log(extractInformation("Upper and lower 123 ranch milk 125ML (3 * 8)"))
這不是一個好的解決方案,但可以節省一天的時間(JavaScript)。
var str = "Upper and lower ranch milk 125ML (3 * 8)"
f = str.match(/\d+ML/g)[0]
//"125ML"
[x,y] = str.split(f)
//Array [ "Upper and lower ranch milk ", " (3 * 8)" ]
x
//"Upper and lower ranch milk "
y
//" (3 * 8)"
"Upper and lower ranch milk 125ML (3 * 8)".partition(/\d+ML/)
# => ["Upper and lower ranch milk ", "125ML", " (3 * 8)"]
"Upper and lower ranch milk 125ML (3 * 8)".partition(/\d+ML/).map(&:strip)
# => ["Upper and lower ranch milk", "125ML", "(3 * 8)"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.