[英]javascript: how can I split this command line string using spaces but args contain spaces
the command line string I am trying to parse is as such: 我试图解析的命令行字符串是这样的:
screenshotz [ 'li[title="about us"] a', 3,2 ]
div.react-bs-container-body tr > td:nth-child(1)
I am expecting the following 3 items in a list: 我期望列表中包含以下3个项目:
[`screenshotz`,`['li[title="about us"] a', 3,2]`,
`div.react-bs tr > td:nth-child(1)`]
I am doing a command.split(/[Az] /g)
, however, I end up with much more than 3, it takes account into every single space inside the second and last argument. 我正在执行
command.split(/[Az] /g)
,但是最后得到的结果远远超过3,它考虑了第二个参数和最后一个参数中的每个空格。
Essentially I need to allow just about any type of characters, however one clear rule is that a user can submit without the [ ... ]
characters: 本质上,我几乎需要允许任何类型的字符,但是一个明确的规则是,用户可以不使用
[ ... ]
字符来提交:
screenshot div.react-bs-container-body tr > td:nth-child(1)
which should return [screenshot, div.react-bs....]
应该返回
[screenshot, div.react-bs....]
It always follows this rule, the [...]
cannot come after the css selectors. [...]
始终遵循此规则,css选择器之后不能出现[...]
。
How can I make split a string using the spaces on the "outside" and not inside the individual argument parameter in a command? 如何使用命令“外部”而不是单个参数内部的空格分割字符串?
So it shouldn't split a space in an argument parameter string. 因此,不应在参数参数字符串中分隔空格。 for instance that css has a ton of space but it should all be one arg param.
例如,css有很多空间,但都应该是一个arg参数。
Your regular expression is causing the string to be split on any alpha characters followed by space. 您的正则表达式导致字符串被拆分为任何字母字符,后跟空格。 You need to break down the command line string into its components:
您需要将命令行字符串分解为以下组件:
screenshot
at the beginning of the string, followed by a space. screenshot
位于字符串的开头,后跟一个空格。 [...]
[...]
Each of these components, grouped in RegEx, can be represented by: 在RegEx中分组的每个组件都可以表示为:
(screenshot)␠
(\\[.+\\])?
␠?(.+)
(screenshot).+?([.+]) ?(.+) (屏幕截图)。+?([。+])?(。+)
I am assuming the z
in screenshotz
is a typo. 我假设
screenshotz
的z
是一个错字。
Using split
results in blank results at the start and end of the array, instead, I recommend using matchAll
: 在数组的开头和结尾使用
split
结果会导致结果空白,我建议使用matchAll
:
command = `screenshot [ 'li[title="about us"] a', 3,2 ]
div.react-bs-container-body tr > td:nth-child(1)`
Array.from(command.matchAll(/(screenshot) (\[.+\]) ?(.+)/sg))
The result is: 结果是:
Array(4)
0: "screenshot [ 'li[title="about us"] a', 3,2 ] ↵div.react-bs-container-body tr > td:nth-child(1)"
1: "screenshot"
2: "[ 'li[title="about us"] a', 3,2 ]"
3: "↵div.react-bs-container-body tr > td:nth-child(1)"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.