Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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
Regex 正则表达式,url的子字符串,从开始到某个字符的第三个字符_Regex_Powershell_Substring - Fatal编程技术网

Regex 正则表达式,url的子字符串,从开始到某个字符的第三个字符

Regex 正则表达式,url的子字符串,从开始到某个字符的第三个字符,regex,powershell,substring,Regex,Powershell,Substring,好的,我有一系列的URL,从 http://www.test.com/sasa http://www.test.com/sasdassasdssda http://www.test.com/ewewewewsasa http://www.test.com 我想做的是只取每个url的子字符串,从开始到第三个/如果没有第三个/取原始字符串 基本上,我想知道如何得到第三个/的位置,因为我假设如果没有第三个/那么它将是-1,所以我可以抓住这个位置,如果不是-1,则执行子字符串位。 无论如何,我已经受够

好的,我有一系列的URL,从

http://www.test.com/sasa
http://www.test.com/sasdassasdssda
http://www.test.com/ewewewewsasa
http://www.test.com
我想做的是只取每个url的子字符串,从开始到第三个/如果没有第三个/取原始字符串

基本上,我想知道如何得到第三个/的位置,因为我假设如果没有第三个/那么它将是-1,所以我可以抓住这个位置,如果不是-1,则执行子字符串位。
无论如何,我已经受够了闲逛。如何找到第三个斜杠的位置?

听起来您希望URI没有路径(第三个斜杠后面的段)和尾随的
/
本身

最简单的方法是将字符串转换为实际的URI对象,然后使用
AbsoluteUri
PathAndQuery
属性来计算在何处执行以下操作:

function Get-UriSchemeAndAuthority
{
    param(
        [string]$InputString
    )

    $Uri = $InputString -as [uri]
    if($Uri){
        $FullUri = $Uri.AbsoluteUri
        $Path = $Uri.PathAndQuery

        $SlashIndex = $FullUri.Length - $Path.Length

        return $FullUri.Substring(0,$SlashIndex)
    } else {
        throw "Malformed URI"
    }
}
适用于所有测试用例:

PS C:\> Get-UriSchemeAndAuthority http://www.test.com/sasa
http://www.test.com
PS C:\> Get-UriSchemeAndAuthority http://www.test.com/sasdassasdssda
http://www.test.com
PS C:\> Get-UriSchemeAndAuthority http://www.test.com/ewewewewsasa
http://www.test.com
PS C:\> Get-UriSchemeAndAuthority http://www.test.com
http://www.test.com

或者,使用
方案
权限
属性,并从这些属性中创建一个新字符串(使其更加简洁):

您可以使用
^([^/]*/){2}[^/]*
regex。
function Get-UriSchemeAndAuthority
{
    param(
        [string]$InputString
    )

    $Uri = $InputString -as [uri]
    if($Uri){
        return $("{0}://{1}" -f $Uri.Scheme,$Uri.Authority)
    } else {
        throw "Malformed URI"
    }
}