Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string with string as delimiter

I'm trying to split a string in a batch file using a string (rather than a character) as the delimiter.

The string has the format:

string1 by string2.txt

The delimiter is by (yes, space, the word 'by', followed by space). The output I want is:

string1

string2

So, basically, split the string into 2 parts by the delimiter by and remove the suffix from the second string. How can I do this?

like image 953
Bud Avatar asked May 12 '14 03:05

Bud


People also ask

How do you split a string with a delimiter?

You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe.

Can a string be a delimiter?

In Java, delimiters are the characters that split (separate) the string into tokens. Java allows us to define any characters as a delimiter. There are many string split methods provides by Java that uses whitespace character as a delimiter. The whitespace delimiter is the default delimiter in Java.

How do I split a string into string?

Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.

How split a string using delimiter in C#?

Split(char[]) Method This method is used to splits a string into substrings that are based on the characters in an array. Syntax: public String[] Split(char[] separator); Here, separator is a character array that delimits the substrings in this string, an empty array that contains no delimiters, or null.


Video Answer


1 Answers

I recently discovered an interesting trick that allows to "Split String With String As Delimiter", so I couldn't resist the temptation to post it here as a new answer. Note that "obviously the question wasn't accurate. Firstly, both string1 and string2 can contain spaces. Secondly, both string1 and string2 can contain ampersands ('&')". This method correctly works with the new specifications (posted as a comment below Stephan's answer).

@echo off
setlocal

set "str=string1&with spaces by string2&with spaces.txt"

set "string1=%str: by =" & set "string2=%"
set "string2=%string2:.txt=%"

echo "%string1%"
echo "%string2%"

For further details on the split method, see this post.

like image 151
Aacini Avatar answered Oct 20 '22 08:10

Aacini