【问题标题】:Extract substring from string using javascript regular expressions使用javascript正则表达式从字符串中提取子字符串
【发布时间】:2015-12-03 07:21:01
【问题描述】:

我是 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');

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

【问题讨论】:

  • 我正在使用这个工具:regex101.com 很有帮助
  • 谢谢...帮助队友!!!

标签: javascript regex


【解决方案1】:

正则表达式不应包含在引号中。使用[^;]+ 选择直到; 之前的任何内容。

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);

【讨论】:

    【解决方案2】:

    思考底层语法/句法很有用:

    string := '密码=' 密码 ';' ...

    所以你要匹配非分号字符。

    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
    

    【讨论】:

      【解决方案3】:

      你可以试试这个/Password.*;/

      所以你开始寻找一个以Password开头的字符串,然后是任何字符,直到你找到;

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

      【讨论】:

        【解决方案4】:

        避免使用潜在的保留字。

        您的第一个正则表达式有效,您只是在它周围添加了无用的引号。删除它会起作用。

        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 ', '');
        

        【讨论】:

          猜你喜欢
          • 2010-10-14
          • 1970-01-01
          • 1970-01-01
          • 2014-10-17
          • 2014-08-25
          • 2021-09-25
          • 1970-01-01
          • 2023-02-09
          相关资源
          最近更新 更多