2014-10-08 22 views
0

我想使用PowerShell合并数百个.rtf文件。什么REGEX模式会让我成为一个字符串的最后部分?

这里的格式: 一堆CSS的东西,然后我想要的部分.....

{\rtf1\ansi {\fonttbl{\f0 Arial;}}{\colortbl\red255\green255\blue255;}{\stylesheet 
}\paperw11685\paperh1560\margl600\margr600\margt600\margb600\pard\plain\f0\fs28\cf0 
\ql\li75\ri75\fi0\b Instructions: } 

在这种情况下,我希望保留 “说明:”

{\rtf1\ansi {\fonttbl{\f0 Arial;}}{\colortbl\red255\green255\blue255;}{\stylesheet 
}\paperw10530\paperh1920\margl600\margr600\margt600\margb600\pard\plain\f0\fs28\cf0 
\ql\li75\ri75\fi0\b You will be presented with fifty (50) questions which are ran 
domly selected from a pool of hundreds of questions. } 

在这种情况下,我希望保留“您将会看到五十(50)个问题,这些问题是从数百个问题池中选出来的,并且是从 中选出的。”

PowerShell脚本是这样的:

$files = (dir *.rtf) 
$outfile = "AllQuestions.rtf" 
$files | %{ 
$_.Name | Add-Content $outfile 
$MyVar = Get-Content $_.Name  
$MyVar=$MyVar -replace ".*b\s","" | Add-Content $outfile 
} 

我的意图是UP更换所有的字符为 “\ B” 与虚无( “”)。 我用/。 b \ S /(FWD斜面作为定界符, = “一切零次或多次”,B \ S =字母B和一个空格)。我部分成功;它的汽提部分

{\rtf1........cf0 
\ql\li75\ri75\fi0\b Instructions: } 

{\rtf1........cf0 
Instructions: } 

这让我觉得在cf0之后有一个换行。我试图去掉所有的换行符

-replace "\n*","" 

没有改变字符串。

但是我想转储所有以前的字符串(从{\ rtf1 ....到最终文本之前的右边)&留下那个结束文本.....在这一点上,我将采取拖尾“}”转储它在随后更换

回答

1

可以使用向后看正则表达式 添加捕获组(*)。和非捕获组(?:}),以便它恰好匹配为止}

(?<=\\b)(.*)(?: })$ 
+1

我知道OP说他们会接受尾部的'}',但他们确实声明他们并不是真的想要它。你可能想要设置一个捕获组,然后在那里设置一个非捕获组。 '(?<= \\ b)(。*)(?:})$' – TheMadTechnician 2014-10-08 18:54:41

+0

@TheMadTechnician,完美,谢谢,更新了答案。 – radar 2014-10-08 19:04:48

+0

耶。工作。谢谢。你能解释一下吗?<=这部分?我认为\\ b正在逃避反斜杠,字母b和空格。 ....最后,你锚定一个$从最后开始向后搜索? – jazaddict 2014-10-08 20:02:59

0

试试这个正则表达式($是指一行的结尾),以获得“说明:”或“你将被提出五十(50)个问题是主宰从数百个问题池中选择“”部分:

\\b(.*)}$ 
+0

这将匹配一切都会过去的第一个' \ b'找到。在这个例子中,它将匹配'lue255;} {\ stylesheet } \ paperw10530 \ paperh1920 \ margl600 \ margr600 \ margt600 \ margb600 \ pard \ plain \ f0 \ fs28 \ cf0 \ ql \ li75 \ ri75 \ fi0 \ b您将会被呈现五十(50)个从数百个问题池中选出的 的问题。 ' – TheMadTechnician 2014-10-08 18:44:05

0

替换此:

.*?\\b(?!.*?\\b)[ ]*([^}]+) 

要:

$1 

$MyVar -replace $regex,'$1' 

Demo

0

您可以使用正则表达式多:

$text = (@' 
{\rtf1\ansi {\fonttbl{\f0 Arial;}}{\colortbl\red255\green255\blue255;}{\stylesheet 
}\paperw10530\paperh1920\margl600\margr600\margt600\margb600\pard\plain\f0\fs28\cf0 
\ql\li75\ri75\fi0\b You will be presented with fifty (50) questions which are randomly selected from a pool of hundreds of questions. } 
'@) 

$text -replace '(?ms).+\\b([^}]+)}.*','$1' 

You will be presented with fifty (50) questions which are randomly selected from a pool of hundreds of questions. 

使用-raw交换机获取内容读取该文件为多行文字:

$files = (dir *.rtf) 
$outfile = "AllQuestions.rtf" 
$files | %{ 
$_.Name | Add-Content $outfile 
$MyVar = Get-Content $_.Name -Raw  
$MyVar=$MyVar -replace '(?ms).+\\b([^}]+)}.*','$1' | Add-Content $outfile 
} 
相关问题