Extract segments between delimiters from a string
Suppose you have a string containing specific delimited content that you wish to extract. For example, given the string:
"super example of string key : text I want to keep - end of my string"
You may need to isolate the part between "key:" and "-". Instead of relying on complex regular expressions, there is an easier way.
Isolate the desired text using the Substring method:
To accomplish this task efficiently, use the Substring method. For example:
<code> string St = "super example of string key : text I want to keep - end of my string"; int pFrom = St.IndexOf("key : ") + "key : ".Length; int pTo = St.LastIndexOf(" - "); string result = St.Substring(pFrom, pTo - pFrom);</code>
In this code, IndexOf finds the starting position of the desired substring and LastIndexOf finds the ending position. The length of the prefix ("key : ") is added to pFrom to exclude it from the results. The Substring method then isolates the string fragment, providing the text you need to extract.
The above is the detailed content of How Can I Easily Extract Text Between Delimiters in a String?. For more information, please follow other related articles on the PHP Chinese website!