在给定变量之前从字符串中删除所有内容

时间:2019-06-26 09:44:53

标签: powershell

我有一个字符串some\string/with/**/special\chars\haha。在变量中,我持有chars字符串,并尝试删除chars之前和包括的所有内容,因此预期的输出为\haha

我尝试过……

$temp = "some\string/with/**/special\chars\haha"
$tmp="chars"
$temp -replace '(?s)^.*$tmp', ''

$temp -replace '(?s)^.*$([regex]::Escape($tmp))', ''

,但是唯一有效的方法是将字符串直接置于regex条件中。仅此示例提供了预期的输出:

$temp -replace '(?s)^.*chars', ''

我在做什么错了?

编辑。: 我需要在正则表达式中使用变量,因为我要遍历多个字符串,而并非总是要删除的部分具有相同的字符串(例如:some\string/with/**/special\chars\haha -> \hahaC:\st/h/*/1234\asdf\x -> \x)。因此,总而言之,我在正则表达式中使用变量时遇到了问题,而不是正则表达式本身,因为当我用字符串替换变量时,正则表达式本身就可以正常工作了(如上所示)

2 个答案:

答案 0 :(得分:3)

尝试

$temp = "some\string/with/**/special\chars\haha"
$tmp="chars"
$regex = '(?s)^.*' + $tmp
$temp -replace $regex, ''

答案 1 :(得分:0)

看起来像是因为您在正则表达式中使用单引号而不是双引号。这意味着未使用变量second.get('/students/:id', (req, res) => { db.collection('students').find({"_id": ObjectID(req.body._id)}).toArray((err,result) => { if(!err) { res.send(result); } else { console.log(err); } }); });

这是您的代码的外观:

$tpm

您的代码使用的是$ tmp而不是$ tmp变量中的实际值。