# How remove specified substring and everything after it to the end of a string?

If I have, say, the string,

txt = "now is the time for all (good) men"


then I want to remove the substring beginning with "for" and ending at the end of the string, namely, remove:

subtext = "for all (good) men"

I do realize that an expression of the form StringReplace[txt, regex ->""] or StringReplace[txt, pattern->""] will do it, but I don't know what regular expression or pattern to use.

The part of the substring to be omitted definitely begins with the specific text "for", but anything could follow it.

• StringReplace[txt, "for" ~~ ___ -> ""]
– paw
Oct 26 '15 at 0:21
• You don't have to use a regular expression; a string expression will also work: for example, "for" ~~ ___ ~~ EndOfString. You can see the corresponding regular expression using StringPatternPatternConvert. In this case it is (?ms)for.*\z. Oct 26 '15 at 0:22
• That works. Want to make it an Answer? And do I really need the part ~~~ EndOfSting? Oct 26 '15 at 0:24
• @paw: Please post your comment as an answer, as it seems to supply a simpler method than using a regular expression. Oct 26 '15 at 21:22

The desired replacement rule can be formulated using string expressions:

"for" ~~ ___-> ""


The pattern represents the concatenation of the string "for" with any sequence of zero or more characters.

Example:

txt = "now is the time for all (good) men";
StringReplace[txt, "for" ~~ ___ -> ""]

"now is the time "


This is how to do it without patterns:

StringDrop[
txt,
StringPosition[txt, "for"][[1, 1]] ;;
]
(* Out: "now is the time " *)


With patterns you have a few different options, as people have remarked in the comments. They gave you the string pattern version, this is the regular expression version:

StringReplace[txt, RegularExpression["for.*$"] -> ""] (* Out: "now is the time " *)  where . denotes any character, * denotes zero or more times, and $ denotes the end of the string.

(I see now that Oleksandr gave a regular expression as well, I didn't see that when I wrote the answer, but I'll let it remain.)

• How get the regular expression to work in case the substring to be deleted begins with, or otherwise includes, special characters such as ( that have special meaning in regexes? I tried the usual method of trying to escape, as StringReplace["now is the time (for) all good men", RegularExpression["$$for$$.*$"] -> ""] but that just returns the original string. Oct 26 '15 at 19:46 • @murray You can resort to this instead: RegularExpression["[(]for[)].*$"] - square brackets in regex means "any of these characters" and in this case we only list one character, so it only matches that one. Oct 26 '15 at 20:05
• Thanks for the fix to using RegularExpression`. I'm still happier using a Wolfram Language string expression. Oct 27 '15 at 2:40