Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 筛选随机的逗号和空格字符串_Powershell_Replace_Filter_Split - Fatal编程技术网

Powershell 筛选随机的逗号和空格字符串

Powershell 筛选随机的逗号和空格字符串,powershell,replace,filter,split,Powershell,Replace,Filter,Split,我有一个由用户生成的字符串,我想在逗号处拆分它 当用户创建此字符串时,他们可能会在逗号之间添加额外的逗号或空格,这些逗号或空格不有用或不需要,或者在以后的脚本中导致问题;e、 g: , ,, ,, ,H30332,B6235,, ,,,,Y65454,,,M7373 这应该被过滤到: H30332,B6235,Y65454,M7373 我尝试了一些-splits和-replaces,但我无法准确地找到我需要的,我要么在它们之间留有空格,要么没有逗号,也没有空格。编者注:这个

我有一个由用户生成的字符串,我想在逗号处拆分它

当用户创建此字符串时,他们可能会在逗号之间添加额外的逗号或空格,这些逗号或空格不有用或不需要,或者在以后的脚本中导致问题;e、 g:

,   ,, ,,   ,H30332,B6235,,      ,,,,Y65454,,,M7373
这应该被过滤到:

H30332,B6235,Y65454,M7373
我尝试了一些
-split
s和
-replace
s,但我无法准确地找到我需要的,我要么在它们之间留有空格,要么没有逗号,也没有空格。

编者注:这个Java答案是在OP澄清寻求PowerShell解决方案之前发布的

此代码提供输出H30332、B6235、Y65454、M7373

    String str = ",   ,, ,,   ,H30332,B6235,,      ,,,,Y65454,,,M7373";

    String regex = "\\s";
    String replacement = "";
    String pattern = "(,*)(,)";

    str = str.replaceAll(regex, replacement);

    str = str.replaceAll(pattern, ",");
然后可以在开始时删除“,”

    str = str.substring(1);
  • -替换“[,]+”,“,”
    用一个逗号替换任何非空的空格和/或逗号

  • .Trim(',')
    删除任何前导或尾随逗号

上述结果可根据需要生成H30332、B6235、Y65454、M7373


($string-replace'、+\s*'、'、'-replace'\s*、+'、'、'、').Trim('、')

我明白了。由于这是一个不太直接的几乎重复现在接受的答案,我可以建议你删除它吗?如果您确实想保留它,请将其正确格式化。
$rawList = ',   ,, ,,   ,H30332,B6235,,      ,,,,Y65454,,,M7373'
($rawList -replace '[, ]+', ',').Trim(',')