Split方法按包含空格的字符串拆分

时间:2018-10-10 16:52:32

标签: powershell split

很抱歉,这很明显,但是我已经尝试了很多事情才能使它起作用……在VB(我更熟悉)中,我相信会很好。

我正在尝试使用e分隔符“-”分割字符串。 空格很关键,因为字符串的其他地方有“-”,但不能分隔。

resources :controller_name, only: %i(index)
  or
resources :controller_name, only: [:index]

(在我的大脑中)这个应该返回3个元素:

This-string
contains
some-hyphens

不幸的是,我得到9个以上的元素,具体取决于我使用"This-string - contains - some-hyphens".Split(' - ') 方法的方式。

This
string


contains


some
hyphens

它显然是在Split上拆分,但似乎也在空格上拆分,而忽略了-格式。

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      17134  228

3 个答案:

答案 0 :(得分:5)

String.Split method overload you're using接受const path = require("path"); const Umzug = require("umzug"); let umzug = new Umzug({ logging: function() { console.log.apply(null, arguments); }, migrations: { path: "./database/migrations", pattern: /\.js$/ }, upName: "up", downName: "down" }); const cmd = process.argv[2].trim(); // this will run your migrations if(cmd=='up') { umzug.up().then(console.log("Migrations committed")); } else if (cmd=='down'){ umzug.down().then(console.log("Migrations revereted")); } ,因此powershell很不错,可以为您分割字符串 。如果要使用字符串,则需要传递char[]

StringSplitOptions

在测试中,我需要使用一元数组运算符'This-string - contains - some-hyphens'.Split((,' - '), [StringSplitOptions]::RemoveEmptyEntries) 来强制解析器使用正确的重载。


更像powershell的方式是使用,运算符,该运算符使用正则表达式进行操作:

-split

答案 1 :(得分:1)

.split方法提供给它时​​,它在提供的字符集中分隔开。这意味着您的结果将在空格或连字符处分开。

如果使用-split,则输入将被视为字符串而不是字符集。

让我们看一个示例(下面提供)

50px

以下输出:

$foo = "This-string - contains - some-hyphens"
$bar = $foo -split(' - ')
$bar

答案 2 :(得分:1)

正在发生的事情是基于一个字符数组的拆分。所以“-”就像被split(“”,“-”)。

在powershell中,可以使用-split。 -Split将其视为完整字符串“-”

"This-string - contains - some-hyphens" -split " - "