使用 JavaScript 正则表达式从字符串中提取子字符串
Extract substring from string using javascript regular expressions
我是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');
它再次返回整个字符串。这里出了什么问题?
正则表达式不应用引号括起来。使用[^;]+
选择任何内容,直到;
。
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=(.*?);/g
^
var 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=(.*?);/g);
document.write(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
你可以简单地试试这个/Password.*;/
因此,您开始寻找开头带有Password
的字符串,然后是任何字符,直到达到;
。
通过使用正则表达式末尾的g
,您可以将其设置为全局,因此您不仅要查找第一个;
,还要查找每个。这可能是你的不起作用的原因。
避免使用潜在的保留字。
您的第一个正则表达式有效,您只是在它周围添加了无用的引号。雷莫维格它会起作用。
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 ', '');
相关文章:
- 如何在Javascript中从字符串中提取某些单词
- innerHTML的子字符串可以在初始调用时提取吗
- 从字符串中提取年份的Javascript正则表达式
- 使用javascript从字符串中提取浮点数
- 如何使用另一个字符串作为模板从字符串中提取数据
- Regex模式匹配,从Javascript中的字符串中提取时间,结果出乎意料
- 正在从字符串中提取日期
- 使用gulp-angular gettext从JS文件中提取字符串不起作用
- 如何在系列数据中包含字符串以提取工具提示点格式
- 通过正则表达式从字符串中提取Url
- 正则表达式,用于从html格式的字符串中提取文本
- Javascript:如何通过Regexp从属性中提取字符串
- 如何删除“"使用javascript从字符串中提取字符
- 如何从由“”分隔的字符串中提取最后一个文本|&”;
- 从html标记格式的字符串中提取键值对
- 简单的javascript字符串提取
- 如何通过jquery或javascript从日期字符串提取日期格式
- 在Javascript中从字符串提取值到数组
- 如何将元组字符串提取到数据结构中
- 我如何从JavaScript中的URL字符串提取值