[英]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.