Since one of SubString's overloads takes only the starting index, first find where serious
(note the trailing space) is and then pick substring from that point plus length of what was searched for.
By putting the search term into a variable, one can access its length as a property. Changing the search term would be easy too, as it requires just updating the variable value instead of doing search and replace for string values.
Like so,
$searchTerm = "serious "
$start = $text.IndexOf($searchTerm)
$text.Substring($start + $searchTerm.length)
sample text, not a joke!
As for a simple regex, use -replace
and pattern ^.*serious
. That would match begin of string ^
then anything .*
followed by seroius
. Replacing that with an empty string removes the matched start of string. Like so,
"This is a very serious sample text, not a joke!" -replace '^.*serious ', ''
sample text, not a joke!
There might be cases in which Extension Methods would be straight-forward solution. Those allow adding new methods to existing .Net classes. The usual solution would be inheriting, but since string is sealed, that's not allowed. So, extension methods are the way to go. One case could be creating a method, say, IndexEndOf
that'll return where search term ends.
Adding .Net code (C# in this case) is easy enough. Sample code is adapted from another answer. The IndexEndOf
method does the arithmetic and returns index where the pattern ended at. Like so,
$code=@'
public class ExtendedString {
public string s_ {get; set;}
public ExtendedString(string theString){
s_ = theString;
}
public int IndexEndOf(string pattern)
{
return s_.IndexOf(pattern) + pattern.Length;
}
public static implicit operator ExtendedString(string value){
return new ExtendedString(value);
}
}
'@
add-type -TypeDefinition $code
$text = "This is a very serious sample text, not a joke!"
$searchTerm = "serious "
$text.Substring(([ExtendedString]$text).IndexEndOf($searchTerm))
sample text, not a joke!