繁体   English   中英

在带有回车的文本中使用正则表达式

[英]Using regex within text with carriage return

我正在使用 powershell 在 txt 中使用正则表达式,但只有当文本不包含回车时它才有效。 我准备了一个这样的示例文件:

the duck is on the table --found!  

the elephant is on  the table --found! 

the cat is  
on the table --NOT found!  :-(

the lion is on the tablet --NOT found but ok ;-)

the dog is on  
the table               --NOT found!  :-(

the turtle isonthe table --NOT found but ok ;-)

the cow is on the              table --found! 

我想要包含“在桌子上”的案例,所以我执行这个:

select-string -path "c:\example.txt" -pattern '([^\w]{1})on([^\w])+the([^\w])+table([^\w]{1})'

这是输出:


example.txt:1:鸭子在桌子上--找到了!

example.txt:2:大象在桌子上--找到了!

example.txt:14:牛在桌子上——找到了!


但我还需要回车的情况! 猫在哪里? 狗在哪里?

谢谢 ;-)

我不确定这是否可以使用Select-String因为它逐行而不是将文件作为单个多行string读取,但这对我有用:

$tmp = New-TemporaryFile

@'
the duck is on the table 

the elephant is on the table 

the cat is
on the table

the lion is on the tablet

the dog is on
the table

the turtle isonthe table

the cow is on the table 
'@ | Set-Content $tmp


$content = Get-Content $tmp -Raw
[regex]::Matches($content, '.*[^\w]on[^\w]+the[^\w]+table[^\w].*') |
Select-Object Index,Value | Format-Table -Wrap

结果:

Index Value                         
----- -----                         
    0 the duck is on the table      
   29 the elephant is on the table  
   62 the cat is                    
      on the table                  
  119 the dog is on                 
      the table                     
  175 the cow is on the table   

如果您只想要单词之间的空格,则最好使用:

'.*\son\s+the\s+table\s.*'

如果你想不区分大小写:

[regex]::Matches($content, '.*[^\w]on[^\w]+the[^\w]+table[^\w].*', [System.StringComparison]::OrdinalIgnoreCase)

通过Select-String-Path-LiteralPath参数提供的文件输入,目标文件将逐行处理,正如Santiago Squarzon 的有用回答中所指出

为了配合跨线模式,文件的内容必须作为一个单一的,多行字符串,这正是传递Get-Content-Raw开关一样

此外,为了报告该多行字符串内的多个匹配项,必须使用Select-String-AllMatches开关

然后可以通过Select-Object输出的Microsoft.PowerShell.Commands.MatchInfo实例的.Matches属性处理结果匹配:

Get-Content -Raw example.txt | 
  Select-String -AllMatches '(?m)^.*?\son\s+the\s+table\b.*$' |
    ForEach-Object {
      foreach ($match in $_.Matches) {
        "[$($match.Value)]"
      }
    }

有关上面使用的正则表达式的说明,请参阅此 regex101.com 页面 [1]

以上产生:

[the duck is on the table]
[the elephant is on  the table]
[the cat is  
on the table]
[the dog is on  
the table]
[the cow is on the              table]

[1] 请注意,尽管regex101.com是一个用于对正则表达式进行可视化、解释和试验的站点,但不支持 PowerShell 使用的.NET正则表达式引擎,但选择类似的引擎(例如 Java)通常会表现出相同的行为,至少从根本上说。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM