简体   繁体   English

如何在数字前的逗号和字母后剪切字符串

[英]How to cut string after comma and letters befor numbers

I have a string我有一个字符串

var numb = "R$ 2000,15"

I would like to cut two last numbers and comma,and R$ with space, to get result => 2000 .我想将最后两个数字和逗号和R$与空格分开,以获得结果 => 2000

I tried with regex: (?,\d{1,5})?(::\d{2}) and it takes result: R$ 2000 .我尝试使用正则表达式: (?,\d{1,5})?(::\d{2})并得到结果: R$ 2000 So now I would like to remove R$ with space.所以现在我想用空格删除 R$。

Any help?有什么帮助吗?

You can simply split on , and then split on space您可以简单地拆分,然后拆分space

 var numb = "R$ 2000,15" let commaSplitted = numb.split(',', 1)[0] // split by `,` let final = commaSplitted.split(' ') // split by space console.log(final)


Or you can use match或者你可以使用匹配

在此处输入图像描述

 let numb = "R$ 2000,15" let num = numb.match(/^R\$\s*([^,]+)/)[1] console.log(num)

You could do it this way if you'd like by capturing the different groups and then outputting the desired group.如果您愿意,可以通过捕获不同的组然后输出所需的组来做到这一点。

The three capture groups match:三个捕获组匹配:

  • $1 = "R$ " $1 = "R$"
  • $2 = Anything $2 =任何东西
  • $3 = ",NN" (where NN is two numbers) $3 = ",NN" (其中 NN 是两个数字)

 const num = "R$ 2000,15"; const exp = new RegExp(/^(R\$\s)(.*)(,\d{2})$/); document.write(num.replace(exp, "$2"));

how about this,这个怎么样,

  var str = "R$ 2000,15";
  var res = str.split(" ");
  res=res[1].split(",");
  res[0]

in this case res[0] is what you looking for, it is working but it may not be the good practice.在这种情况下, res[0] 是您正在寻找的,它正在工作,但它可能不是好的做法。

Try this regular expression:试试这个正则表达式:

 var numb = "R$ 2000,15" numb = numb.replace(/([A-Za-z]+\W+\s{1})([0-9]*)\W+[a-zA-Z0-9]*/, "$2"); console.log(numb);

It removes all letters and symbols and one space in front of the digits它删除所有字母和符号以及数字前面的一个空格

and

all trailing symbols and letters and numbers from its behind其后面的所有尾随符号、字母和数字

and will give middle number.并会给出中间数。

Try this regex, it should do the trick:试试这个正则表达式,它应该可以解决问题:

/^R\$\s(\d+)((\,\d{2})?)$/

To use it, you can replace like this:要使用它,您可以像这样替换:

let result = myNumber.replace(/^R\$\s(\d+)((\,\d{2})?)$/, "$1");

Note that each group between parentheses will be captured by your regex for replacement, so if you want the set of numbers before the comma you should use the corresponding group (in this case, 1).请注意,括号之间的每个组将被您的正则表达式捕获以进行替换,因此如果您想要逗号之前的一组数字,您应该使用相应的组(在本例中为 1)。 Also note that you should not put your regex between quotes.另请注意,您不应将正则表达式放在引号之间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM