4

我正在尝试使用一些字符作为运算符从文本框中拆分文本。我有一个分组运算符 (") 和一个 "AND" 运算符 (+),就像 google 一样。所以,这段文字:

box +box +"box" "box" "is.a.box" +"is.a.box" +"is a box"

在文本框中返回这个:

myArray[0] = box
myArray[1] = +box
myArray[2] = +
myArray[3] = "box"
myArray[4] = "box"
myArray[5] = "is.a.box"
myArray[6] = +
myArray[7] = "is.a.box"
myArray[8] = +
myArray[9] = "is a box"

相反,我希望它返回这个:

myArray[0] = box
myArray[1] = +box
myArray[2] = +"box"
myArray[3] = "box"
myArray[4] = "is.a.box"
myArray[5] = +"is.a.box"
myArray[6] = +"is a box"

这是我正在使用的正则表达式:

/[\+\w]+|"[^"]+"/g

如何将 " 和 + 符号分开?

4

3 回答 3

4

看看这个:

str.match(/\+?(?:"[^"]*"|[^\s+]+)/g)

+如果可能的话,这将开始。然后它会尝试匹配一个". 如果可以的话,它将尽可能多地使用非"字符和最后的". 如果没有",它将尽可能多地使用非空格、非+字符。

这几乎就是你所拥有的,除了我+在两种可能的情况下都拿出了一个可选的。

又多了一个。如果box"box"应该导致两个匹配box"box"使用它:

str.match(/\+?(?:"[^"]*"|[^\s+"]+)/g)
于 2012-11-20T16:22:25.017 回答
3
/\+?("[^"]*"|[^\s+])+/g

诀窍是将带引号的字符串视为单个字符。我们看起来是非空白、非特殊字符 ( [^\s+]),但我们也会假装带引号的字符串 ( "[^"]*") 是一个字符。

> 'box +box +"box" "box" "is.a.box" +"is.a.box"'.match(/\+?("[^"]*"|[^\s+])+/g)
  ["box", "+box", "+"box"", ""box"", ""is.a.box"", "+"is.a.box""]

> '"string with spaces" +"extended phrase"'.match(/\+?("[^"]*"|[^\s+])+/g)
  [""string with spaces"", "+"extended phrase""]

> 'box+box'.match(/\+?("[^"]*"|[^\s+])+/g)
  ["box", "+box"]
于 2012-11-20T16:22:46.260 回答
0

您想要的结果可以通过对空格的简单拆分来实现。

您可能希望使其更智能并使用以下内容折叠多个空格:

myArray = str.split(/[\s]+/g)

对于您的输入字符串,这将返回您想要的数组:

["box", "+box", "+"box"", ""box"", ""is.a.box"", "+"is.a.box""]
于 2012-11-20T16:31:05.893 回答