代码之家  ›  专栏  ›  技术社区  ›  BrynJ

Javascript-方括号之间的返回字符串

  •  28
  • BrynJ  · 技术社区  · 15 年前

    我只需要返回字符串中方括号内的文本。我有以下正则表达式,但也返回方括号:

    var matched = mystring.match("\\[.*]");
    

    字符串只能包含一组方括号,例如:

    Some text with [some important info]
    

    5 回复  |  直到 15 年前
        1
  •  123
  •   Alex Barrett    15 年前

    ? 使匹配的“ungreedy”,因为这可能是您想要的。

    var matches = mystring.match(/\[(.*?)\]/);
    
    if (matches) {
        var submatch = matches[1];
    }
    
        2
  •  17
  •   Stephen Sorensen    15 年前

    由于javascript不支持捕获,因此必须对其进行破解。考虑这一选择,采取相反的方法。与其捕获括号内的内容,不如删除括号外的内容。因为只有一组括号,所以它应该可以正常工作。我通常使用这种技术剥离前导和尾随空格。

    mystring.replace( /(^.*\[|\].*$)/g, '' );
    
        3
  •  7
  •   Wiktor Stribiżew    4 年前

    要匹配两个相邻的开方括号和闭方括号之间的任何文本,可以使用以下模式:

    \[([^\][]*)]
    (?<=\[)[^\][]*(?=])
    

    regex demo #1 regex demo #2 :第二个带有lookarounds的正则表达式在兼容ECMAScript 2018的JavaScript环境中受支持。如果需要支持较旧的环境,请使用第一个带有捕获组的正则表达式。

    :

    • (?<=\[) -与前面紧跟着 [
    • [^\][]* -零或更多( * ] ([^\][]*) 版本是相同的模式 捕获
    • (?=]) -与紧跟其后的位置匹配的正向前瞻 ] ]

    现在,在代码中,您可以使用以下内容:

    const text = "[Some text] ][with[ [some important info]";
    console.log( text.match(/(?<=\[)[^\][]*(?=])/g) );
    console.log( Array.from(text.matchAll(/\[([^\][]*)]/g), x => x[1]) );
    // Both return ["Some text", "some important info"]

    下面是一种使用 RegExp#exec 在循环中:

    var text = "[Some text] ][with[ [some important info]";
    var regex = /\[([^\][]*)]/g;
    var results=[], m;
    while ( m = regex.exec(text) ) {
      results.push(m[1]);
    }
    console.log( results );
        4
  •  5
  •   Praveen    10 年前

    ("\\[(.*)]");
    

    这将返回括号内的模式,作为返回数组中捕获的匹配项

        5
  •  5
  •   ivan0biwan    6 年前

    replace map

    "blabla (some info) blabla".match(/\((.*?)\)/g).map(b=>b.replace(/\(|(.*?)\)/g,"$1"))
    
        6
  •  3
  •   Jeremy Stein    15 年前

    顺便说一句,你可能不想要一个贪婪的人 .*

    "\\[.*?]"
    

    "\\[[^\\]]*]"