使用javascript正则表达式从字符串中提取子字符串

使用javascript正则表达式从字符串中提取子字符串,javascript,regex,Javascript,Regex,我不熟悉Javascript中的正则表达式 这根绳子看起来像 Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517;Persist Security Info=False;User ID=AppleTurnover;Initial Catalog=ProductDB;Data Source=Sydney 我正试图从中提取一点 Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517 从这个字符串 因此,我: string="`Password=

我不熟悉Javascript中的正则表达式

这根绳子看起来像

Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517;Persist Security Info=False;User ID=AppleTurnover;Initial Catalog=ProductDB;Data Source=Sydney
我正试图从中提取一点

Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517
从这个字符串

因此,我:

string="`Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517;Persist Security Info=False;User ID=AppleTurnover;Initial Catalog=ProductDB;Data Source=Sydney"
substring=string.match('/Password=(.*);/g');

它再次返回整个字符串。这里出了什么问题?

Regex不应该用引号括起来。使用
[^;]+
选择任何内容,直到

var password = string.match(/Password=([^;]+)/)[1];
string=“`Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517;Persist Security Info=False;User ID=AppleTurnover;Initial Catalog=ProductDB;Data Source=Sydney);
var password=string.match(/password=([^;]+)/)[1];

document.write(password);
您只需尝试此
/password.*;/

因此,您开始查找开头带有
密码的字符串,后跟任意字符,直到找到

var password = string.match(/Password=([^;]+)/)[1];

通过在正则表达式末尾使用
g
,您将其设置为全局,因此您不仅要查找第一个
,而且要查找每一个。这可能就是您的正则表达式不起作用的原因。

考虑底层语法/语法非常有用:

字符串:='Password='Password';'

因此,您希望匹配非分号字符

string="`Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517;Persist Security Info=False;User ID=AppleTurnover;Initial Catalog=ProductDB;Data Source=Sydney"
/Password=([^;]+)/.exec(string)[0] // or [1] if you want just the password

避免使用潜在的保留字

你的第一个正则表达式工作了,你只是在它周围添加了无用的引号。Removig它会工作的

var myString = "`Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517;Persist Security Info=False;User ID=AppleTurnover;Initial Catalog=ProductDB;Data Source=Sydney"
var mySubstring = myString.match(/Password=(.*);Persist /g); // Remove the ' around the regex
var thePassword = mySubstring[0].replace('Password=', '');
thePassword = thePassword.replace(';Persist ', '');

我正在使用这个工具:帮助很多谢谢你…帮助了伴侣!!!