繁体   English   中英

正则表达式仅引用字符串匹配项(不包括数字)

[英]regexp to quote only string matches (not numbers)

我在用字符串挣扎:

"some text [2string] some another[test] and another [4]";

尝试引用除[]中的数字以外的所有值,以便可以将其转换为

"some text ['2string'] some another['test'] and another [4]"

谢谢。

您需要一个正则表达式

  • 匹配[]之间的内容,即[ ,除]外的任意数量的字符,然后是]
  • 断言这里除了数字外还至少还有一个其他字符。

您可以使用字符类否定超前断言来解决此问题:

result = subject.replace(/\[(?!\d+\])([^\]]*)\]/g, "['$1']");

说明:

\[      # Match [
(?!     # Assert that it's impossible to match...
 \d+    # one or more digits
 \]     # followed by ]
)       # End of lookahead assertion
(       # Match and capture in group number 1:
 [^\]]* # any number of characters except ]
)       # End of capturing group
\]      # Match ]

我会尝试类似\\[(\\d*?[az]\\w*?)] 这应该与任何[...]只要有至少一个字母里面。 如果下划线( _ )无效,请用[az]替换\\w末尾。

  • \\[仅仅是一个简单的匹配[ ,但由于在特殊含义进行转义[
  • \\d*? 将匹配任意数量的数字(或不匹配任何数字),但要满足匹配要求的位数应尽可能少。
  • [az]将匹配给定范围内的任何字符。
  • \\w*? 会匹配所有“单词”(字母数字)字符(字母,数字和下划线),但又要尽可能少地匹配。
  • ]是另一种简单的匹配方式,不必逃避,因为它不会引起误解(在此级别没有开放[ )。 可以对其进行转义,但这通常是样式首选项(取决于实际的正则表达式引擎)。

如果性能不是大问题,则可以使用更长的但更干净的IMO方法:

var string = "some text [2string] some another[test] and another [4]";
var output =  string.replace(/(\[)(.*?)(\])/g, function(match, a, b, c) {
  if(/^\d+$/.test(b)) {
    return match;
  } else {
    return a + "'" + b + "'" + c;
  }
});
console.log(output);

您基本上将方括号内的每个表达式匹配,然后测试以查看是否为数字。 如果是,则按原样返回字符串,否则在特定位置插入引号。

输出:

some text ['2string'] some another['test'] and another [4]

您可以用此正则表达式替换它

input.replace(/(?!\d+\])(\w+)(?=\])/g, "'$1'");

另一个为您的尝试添加简单正则表达式的解决方案:

str.split('[').join("['").split(']').join("']").replace(/\['(\d+)'\]/, "[$1]");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM