从字符串中拉出数字值

时间:2018-02-16 17:53:13

标签: javascript regex

所以我需要从字符串中提取一个数字值。我目前有一个可行的解决方案,但我觉得也许我可以使用正则表达式来改进它。

这是我的工作解决方案

var subject = "This is a test message [REF: 2323232]";

if(subject.indexOf("[REF: ") > -1){
  var startIndex = subject.indexOf("[REF: ");
  var result = subject.substring(startIndex);
  var indexOfLastBrace = result.indexOf("]");
  var IndexOfRef = result.indexOf("[REF: ");
  var ticketNumber = result.substring(IndexOfRef + 6, indexOfLastBrace);

  if(!isNaN(ticketNumber)){
    console.log("The ticket number is " + ticketNumber)
    console.log("Valid ticket number");
  }
  else{
    console.log("Invalid ticket number");
  }
}

正如你所看到的那样,我试图从“[REF:”字符串后面提取数字值。

4 个答案:

答案 0 :(得分:2)



// Change of the text for better test results
var subject = "hjavsdghvwh jgya 16162vjgahg451514vjgejd5555v fhgv f 262641hvgf 665115bs cj15551whfhwj511";
var regex = /\d+/g;
let number = subject.match( regex )
console.log(number)




它现在将返回数组,如果找不到匹配项,它将返回null。 在大多数情况下,当我使用这个正则表达式时,我得到完美的结果,除非字符串包含十进制值。

答案 1 :(得分:1)

 object HelloScala extends App{

      Seq(Seq("A","B","C"),Seq("A","B","C")).map{ rec =>
          val rec2 = rec.zipWithIndex.map{ case (field, i) =>
                    if (field == "B")
                        None
                    else
                        field + i
          }
          println(rec2.flatten)
      }
 }

答案 2 :(得分:1)

这将提取数字

var subject = "This is a test message [REF: 2323232]";
var onlyNum = subject.replace(/.*(:\s)(\d*)\]$/,'$2');
console.log(onlyNum)

这里,相同但数字现在是真正的int

var subject = "This is a test message [REF: 2323232]";
var onlyNum = parseInt(subject.replace(/.*(:\s)(\d*)\]$/,'$2'));
console.log(onlyNum)

答案 3 :(得分:1)

如果你不想使用正则表达式(我倾向于远离它们,即使我知道它们很强大),这是另一种方法:



// Your code:
/*var subject = "This is a test message [REF: 2323232]";

if(subject.indexOf("[REF: ") > -1){
  var startIndex = subject.indexOf("[REF: ");
  var result = subject.substring(startIndex);
  var indexOfLastBrace = result.indexOf("]");
  var IndexOfRef = result.indexOf("[REF: ");
  var ticketNumber = result.substring(IndexOfRef + 6, indexOfLastBrace);

  if(!isNaN(ticketNumber)){
    console.log("The ticket number is " + ticketNumber)
    console.log("Valid ticket number");
  }
  else{
    console.log("Invalid ticket number");
  }
}*/

// New code:
const subject = "This is a test message [REF: 2323232]";
const codeAsString = subject.split('[REF: ')[1]
  .split(']')
  .join('');

if (!isNaN(parseInt(codeAsString))) {
  console.log('Valid ticket number: ', parseInt(codeAsString));
}
else {
  console.log('Invalid ticket number: ', codeAsString);
}