【问题标题】:Split number and string from the value using java script or regex使用 javascript 或正则表达式从值中拆分数字和字符串
【发布时间】:2014-06-24 07:02:39
【问题描述】:

我有一个值“4.66lb”

我想使用正则表达式分隔“4.66”和“lb”。

我尝试了下面的代码,但它只分隔数字“4,66”!但我想要 4.66 和 lb 的值。

var text = "4.66lb";
var regex = /(\d+)/g;
alert(text.match(/(\d+)/g));

【问题讨论】:

  • 你试过追加([a-z]+)吗?

标签: javascript regex string numbers


【解决方案1】:

试一试:

var res = text.match(/(\d+(?:\.\d+)?)(\D+)/);

res[1] 包含 4.66
res[2] 包含 lb

为了也匹配4/5lb,您可以使用:

var res = text.match(/(\d+(?:[.\/]\d+)?)(\D+)/);

【讨论】:

  • 又短又甜,+1。 :)
  • 嘿,我还有另一种情况,数字可以是 4/5lb,所以在这种情况下,我需要拆分 4/5 和 lb....那么这个正则表达式是什么?
  • @user3770003:用斜杠替换点:/(\d+(?:\/\d+)?)(\D+)/
【解决方案2】:

你也可以使用字符类,

> var res = text.match(/([0-9\.]+)(\w+)/);
undefined
> res[1]
'4.66'
> res[2]
'lb'

【讨论】:

    【解决方案3】:

    让我用一个例子来解释

    var str = ' 1 ab 2 bc 4 dd';   //sample string
    
    str.split(/\s+\d+\s+/)
    result_1 = ["", "ab", "bc", "dd"]  //regex not enclosed in parenthesis () will split string on the basis of match expression
    
    str.split(/(\s+\d+\s+)/)        //regex enclosed in parenthesis () along with above results, it also finds all matching strings
    result_2 = ["", " 1 ", "ab", " 2 ", "bc", " 4 ", "dd"] 
    
    //here we received two type of results: result_1 (split of string based on regex) and those matching the regex itself
    
    //Yours case is the second one
    //enclose the desired regex in parenthesis
    solution : str.split(/(\d+\.*\d+[^\D])/)
    

    【讨论】:

      猜你喜欢
      • 2023-02-26
      • 2011-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      相关资源
      最近更新 更多