我想从此字符串中提取“.txt”之前的最后4位数字:
09/14/2017 12:00:27 - mtbill_post_201709141058.txt 7577_Delivered: OK
那些代表创建日志的时间,我想将其显示为10:58。我从一个文件中读取,该文件有多行,类似于显示的行。
class Security {
static var isAuthorized = false //change this when the authorisation status changes
class Secret {
static var shared: Secret? {
if Security.isAuthorized {
return Secret()
} else {
return nil
}
}
private init(){} //a new instance of Secret can only be created using the `shared` computed variable, the initializer cannot be called directly from outside the Secret class
func doSomeSecretAction(){
print("Private method called")
}
}
}
Security.Secret.shared //nil
//Security.Secret.init() //if you uncomment this line, you'll get an error saying all initializers are inaccessible
Security.Secret.shared?.doSomeSecretAction() //nil
Security.isAuthorized = true
Security.Secret.shared?.doSomeSecretAction() //function is called
Security.isAuthorized = false
Security.Secret.shared?.doSomeSecretAction() //nil
我尝试用“_”分隔字符串然后计算获取字符串中的字符并尝试用“Substring”命令分隔,但是我收到以下错误。
使用“2”参数调用“Substring”的异常:“StartIndex不能 小于零。参数名称:startIndex“
在行:6 char:5 + $ folder2 = $ SC.Substring($ len - 12,42)
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- CategoryInfo:NotSpecified:(:) [],MethodInvocationException
- FullyQualifiedErrorId:ArgumentOutOfRangeException
答案 0 :(得分:4)
你可以使用正则表达式“lookahead”。
您要搜索的是一组四位数后跟“.txt”:
$string = "09/14/2017 12:00:27 - mtbill_post_201709141058.txt 7577_Delivered: OK"
$regex = "\d{4}(?=\.txt)"
[regex]::matches($string, $regex).value
答案 1 :(得分:2)
可能有更优雅的解决方案:
$String = '09/14/2017 12:00:27 - mtbill_post_201709141058.txt 7577_Delivered: OK'
$String -Match '.*(?=\.txt)' | Out-Null
$Match = $Matches[0][-4..-1] -Join ''
$Time = [DateTime]::ParseExact($Match, 'HHmm',[CultureInfo]::InvariantCulture)
$Time.ToShortTimeString()
答案 2 :(得分:2)
只需使用Substring
和IndexOf
:
$string="09/14/2017 12:00:27 - mtbill_post_201709141058.txt 7577_Delivered: OK"
$string.Substring($string.IndexOf('.txt')-4, 4)