对字符串中的随机数进行拆分

Javascript Split on random number in string

本文关键字:拆分 随机数 字符串      更新时间:2023-09-26

我有一个字符串,它看起来像这样

TEST/4_James
TEST/1003_Matt
TEST/10343_Adam

我想分割这个字符串得到TEST和"_"之后的名称,什么正则表达式可以用来分割它在"/" + any number + "_" ?

谢谢

使用match,并捕获组:

var james = "TEST/4_James";
matches = james.match(/(.*)'/.*_(.*)/);
console.log(matches[1]); // TEST
console.log(matches[2]); // James

// In order of appearance
(.*)  //matches any character except newline and captures it
'/    //matches a forward slash
.*_   //matches any character except newline followed by an underscore
(.*)  //matches any character except newline (what's left) and captures it

有人提到过:https://regex101.com/我也使用这个,如果你正在学习正则表达式,它是一个很棒的资源,因为它不仅允许你编写和测试它们,而且它解释正则表达式的每一部分及其作用的方式很有教育意义。

如果可以的话,在你的表达式中比.*更明确一点是一个好主意。例如,如果你知道它将是数字或字符,或一个特定的字符串,那么使用一个更明确的模式。我只是使用这个,因为我不确定'TEST'在实际场景中可能包含什么。