简体   繁体   English

在这种情况下如何使用正则表达式?

[英]How to use Regular Expression in this case?

I have got a variable as 30_KK_1_KK_2 我有一个变量为30_KK_1_KK_2

How can i get the value after first KK_ and second KK_ ? 我如何获得第一个KK_和第二个KK_之后的值?

so that the output for First KK_ is 1 and 这样First KK_的输出为1,

for the second KK_ it is 2 第二个KK_是2

I have tried it this way 我已经尝试过这种方式

var str =  "30_KK_1_KK_2";
var n[] = str.split('_KK_');
alert(n[0]);
alert(n[1]);

You have several typos. 您有几种错别字。

1) No string quotes around the string constant 1)字符串常量周围没有字符串引号

2) var n[] is not valid... simply var n 2) var n[]无效...只是var n

3) You need to get elements 1 and 2 as element 0 is "30" 3)您需要获取元素1和2,因为元素0为“ 30”

var str =  "30_KK_1_KK_2";
var n = str.split('_KK_');
alert(n[1]);
alert(n[2]);

JSFiddle: http://jsfiddle.net/TrueBlueAussie/w3mLgowc/1/ JSFiddle: http : //jsfiddle.net/TrueBlueAussie/w3mLgowc/1/

A regular expression is probably overkill for such a simple problem (and the delimiter is fixed). 对于这样一个简单的问题(并且定界符是固定的),正则表达式可能会显得过大。

If you want to really use Regex you can try this code : 如果您想真正使用Regex,可以尝试以下代码:

var str =  "30_KK_1_KK_2";
regex = /.*KK_(\d*)_KK_(\d*)/g;
value_1 = str.replace(regex,"$1");
value_2 = str.replace(regex,"$2");
alert(value_1);
alert(value_2);

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

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