【问题标题】:Javascript regex to extract all characters between quotation marks following a specific wordJavascript正则表达式提取特定单词后引号之间的所有字符
【发布时间】:2014-09-14 01:57:09
【问题描述】:

我有文字:

s.events="event3"
s.pageName="Forum: Index"
s.channel="forum"
s.prop1="Forum: Index"
s.prop2="Index Page"
s.prop36=""
s.prop37=""
s.prop38=""
s.prop39=""
s.prop40="53"
s.prop41="Anonymous"
s.prop42="username"
s.prop43=""
s.prop47=""
s.eVar1="Forum: Index"
s.eVar2="Index Page"
s.eVar36=""
s.eVar37=""

保存在 javascript 中的 var 中,我想提取 s.prop42 引号之间的文本,得到结果:

"username"

我现在拥有的是

    var regex = /\?prop.42="([^']+)"/;
    var test = data.match(regex);

但它似乎不起作用,有人可以帮助我吗?

【问题讨论】:

  • 你为什么要匹配文字问号?为什么你不允许在 double-quote 终止的字符串中使用 single 引号?

标签: javascript regex string match


【解决方案1】:

使用这个:

var myregex = /s\.prop42="([^"]*)"/;
var matchArray = myregex.exec(yourString);
if (matchArray != null) {
    thematch = matchArray[1];
} 

the regex demo 中,查看右侧窗格中的捕获组

说明

  • s\.prop42=" 匹配 s.prop42="(但我们不会检索它)
  • ([^"]*) 中的括号将任何不是 " 的字符捕获到第 1 组:这就是我们想要的
  • 代码获取第 1 组捕获

【讨论】:

  • 不客气,感谢您的绿色复选标记! :)
【解决方案2】:

无法评论上述答案,但我认为 .* 的正则表达式更好,如下所示:

var myregex = /s\.prop42="(.*)"/;
var matchArray = myregex.exec(yourString);
if (matchArray != null) {
    thematch = matchArray[1];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 2016-11-06
    • 2023-03-17
    相关资源
    最近更新 更多