简体   繁体   English

如何在 javascript 中使用正则表达式从另一个字符串中获取特定字符串

[英]How can i get particular string from another string using regex in javascript

My sample code:我的示例代码:

let str = 'myname:is:gopal@gmail.com';
console.log(str.match(":" + "(.*)" + "@")[1]));

returns for above regex => is:gopal // returned value

expected output is => gopal // i want only *gopal*

Note: all the strings are dynamic, except : and @ these special characters.注意:所有字符串都是动态的,除了:@这些特殊字符。

Thanks in advance.提前致谢。

Positive Lookahead and Positive Lookbehind can solve your problem. Positive Lookahead 和 Positive Lookbehind 可以解决您的问题。

UPD : match non-word characters (by @toto) UPD :匹配非单词字符(@toto)

s = 'myname:is:gopal@gmail.com'
s.match(/(?<=:)[^:]+(?=@)/)
// --> ["gopal", index: 10, input: "myname:is:gopal@gmail.com", groups: undefined]

regex101 test here regex101 测试在这里

Many thanks @Mandy8055非常感谢@Mandy8055

let str = "myname:is:gopal@gmail.com";
console.log(str.match('.*:(.*)@.*')[1]); // returns gopal

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

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