简体   繁体   English

Javascript拆分字符串中的随机数

[英]Javascript Split on random number in string

I have a string that will look like one of these this 我有一个看起来像这样的字符串

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

I want to split this string to get TEST and the Name after the "_", what regular expression can use to split it at "/" + any number + "_" ? 我想拆分此字符串以获取TEST和“ _”之后的名称,什么正则表达式可用于将其拆分为"/" + any number + "_"

Thanks 谢谢

Use match , and capturing groups: 使用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

Someone mentioned this: https://regex101.com/ I use this as well and it's an awesome resource if you're learning regular expressions because it not only allows you to write and test them, but it's educational in the way it explains each piece of the regular expression and what it does. 有人提到了这一点: https : //regex101.com/我也使用它,如果您正在学习正则表达式,它是一个很棒的资源,因为它不仅允许您编写和测试它们,而且在解释每个表达式方面都具有教育意义正则表达式及其作用。

Also it's a good idea to be a little more explicit in your expressions than .* if you can. 如果可以的话,在表达式中比.*更加明确也是一个好主意。 For instance if you know that it's going to be numbers or characters, or a particular string then use a more explicit pattern. 例如,如果您知道它将是数字或字符,或者是特定的字符串,则可以使用更明确的模式。 I just used this because I wasn't really sure what 'TEST' might contain in an actual scenario. 我之所以使用它,是因为我不确定在实际情况下可能包含哪些“测试”。

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

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