Powershell在搜索字符串后返回下一个单词

时间:2019-09-05 08:50:03

标签: powershell

如果这是重复的话,我表示歉意,但我徒劳地搜索。我正在尝试在Powershell的搜索字符串之后返回 inclusive 继续的单词。

$wordtest="one two three four"

一个人如何简单地提取包含two three

我徒劳地尝试:

$wordtest.substring($wordtest.IndexOf('two') +1)

($wordtest.Split('two')[1])

我有排他 three查询,其使用方式是:

(($wordtest -split "two")[1].trim() -split ' ')[0]
 three

谢谢。

2 个答案:

答案 0 :(得分:2)

您想做三件事:

  • 将字符串分割成单词
  • 找到您感兴趣的词
  • 得到下一个单词

所以让我们这样做:

$wordtest = "one two three four"
$searchWord = "two";

# split a string into words
$words = $wordtest.Split(" ");

# find the word you're interested in
$wordIndex = $words.IndexOf($searchWord);

# get the next word
$nextWord = $words[$wordIndex + 1];

这是非常简单的代码-例如,它将每个空格字符都视为一个断字符,因此多个空格(和制表符)将引起问题(例如one two three four),对于以下情况,它没有适当的错误处理您找不到找到您的单词,如果没有“下一个单词”,它将引发异常。

无论如何,一旦有了搜索词和下一个词,就可以构造“包含”和“专有”字符串...

$inclusive = "$searchWord $nextWord";
$exclusive = $nextWord;

答案 1 :(得分:2)

您也可以为此使用正则表达式:

$wordtest   = "one two three four"
$searchWord = "two"
if ($wordtest -match "($searchWord\s+\w+)") {
    $matches[0]
}

结果

  

两个三

请注意,如果$searchWord包含正则表达式的特殊字符,例如.$,则需要首先[Regex]::Escape($searchWord)

正则表达式中的特殊字符

Char    Description                         Meaning
------- ----------------------------------- ---------------------------------------------------------
\       Backslash                           Used to escape a special character
^       Caret                               Beginning of a string
$       Dollar sign                         End of a string
.       Period or dot                       Matches any single character
|       Vertical bar or pipe symbol         Matches previous OR next character/group
?       Question mark                       Match zero or one of the previous
*       Asterisk or star                    Match zero, one or more of the previous
+       Plus sign                           Match one or more of the previous
( )     Opening and closing parenthesis     Group characters
[ ]     Opening and closing square bracket  Matches a range of characters
{ }     Opening and closing curly brace     Matches a specified number of occurrences of the previous
相关问题