How to Split a String at The Last Occurence of a Sequence

How to split a string at the last occurence of a sequence

The range(of:...) method of String has a .backwards option
to find the last occurrence of a string.
Then substring(to:) and substring(from:) can be used with the
lower/upper bound of that range to extract the parts of the string
preceding/following the separator:

func parseTuple(from string: String) -> (String, Int)? {

if let theRange = string.range(of: "###", options: .backwards),
let i = Int(string.substring(from: theRange.upperBound)) {
return (string.substring(to: theRange.lowerBound), i)
} else {
return nil
}
}

Example:

if let tuple = parseTuple(from: "Connect###Four###Player###7") {
print(tuple)
// ("Connect###Four###Player", 7)
}

Swift 4 update:

func parseTuple(from string: String) -> (String, Int)? {

if let theRange = string.range(of: "###", options: .backwards),
let i = Int(string[theRange.upperBound...]) {
return (String(string[...theRange.lowerBound]), i)
} else {
return nil
}
}

How to split a string into only two parts, by the last occurrence of the split char?

String#rpartition, e.g.

irb(main):068:0> str = "Angry Birds 2.4.1"
=> "Angry Birds 2.4.1"
irb(main):069:0> str.rpartition(' ')
=> ["Angry Birds", " ", "2.4.1"]

Since the returned value is an array, using .first and .last would allow to treat the result as if it was split in two, e.g

irb(main):073:0> str.rpartition(' ').first
=> "Angry Birds"
irb(main):074:0> str.rpartition(' ').last
=> "2.4.1"

Best way to split string by last occurrence of character?

Updated Answer (for C# 8 and above)

C# 8 introduced a new feature called ranges and indices, which offer a more concise syntax for working with strings.

string s = "My. name. is Bond._James Bond!";
int idx = s.LastIndexOf('.');

if (idx != -1)
{
Console.WriteLine(s[..idx]); // "My. name. is Bond"
Console.WriteLine(s[(idx + 1)..]); // "_James Bond!"
}

Original Answer (for C# 7 and below)

This is the original answer that uses the string.Substring(int, int) method. It's still OK to use this method if you prefer.

string s = "My. name. is Bond._James Bond!";
int idx = s.LastIndexOf('.');

if (idx != -1)
{
Console.WriteLine(s.Substring(0, idx)); // "My. name. is Bond"
Console.WriteLine(s.Substring(idx + 1)); // "_James Bond!"
}

Split string and take last element

The way to do it in SQL :

SELECT SUBSTRING( string , LEN(string) -  CHARINDEX('/',REVERSE(string)) + 2  , LEN(string)  ) FROM SAMPLE;

JSFiddle here http://sqlfiddle.com/#!3/41ead/11

How do I split a string on a fixed character sequence?

public class Splitter {

public static void main(final String[] args) {
final String asd = "this is test ass this is test";
final String[] parts = asd.split("ass");
for (final String part : parts) {
System.out.println(part);
}
}
}

Prints:

this is test 
this is test

Under Java 6. What output were you expecting?

c++ How to split string into two strings based on the last '.'

std::string::find_last_of will give you the position of the last dot character in your string, which you can then use to split the string accordingly.

How do I split a string in Java?

Use the appropriately named method String#split().

String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

Note that split's argument is assumed to be a regular expression, so remember to escape special characters if necessary.

there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".

For instance, to split on a period/dot . (which means "any character" in regex), use either backslash \ to escape the individual special character like so split("\\."), or use character class [] to represent literal character(s) like so split("[.]"), or use Pattern#quote() to escape the entire string like so split(Pattern.quote(".")).

String[] parts = string.split(Pattern.quote(".")); // Split on the exact string.

To test beforehand if the string contains certain character(s), just use String#contains().

if (string.contains("-")) {
// Split it.
} else {
throw new IllegalArgumentException("String " + string + " does not contain -");
}

Note, this does not take a regular expression. For that, use String#matches() instead.

If you'd like to retain the split character in the resulting parts, then make use of positive lookaround. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing ?<= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556

In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing ?= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556

If you'd like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of split() method.

String string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42

Splitting on first occurrence

From the docs:

str.split([sep[, maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).

s.split('mango', 1)[1]

how to get the last part of a string before a certain character?

You are looking for str.rsplit(), with a limit:

print x.rsplit('-', 1)[0]

.rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.

Another option is to use str.rpartition(), which will only ever split just once:

print x.rpartition('-')[0]

For splitting just once, str.rpartition() is the faster method as well; if you need to split more than once you can only use str.rsplit().

Demo:

>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'

and the same with str.rpartition()

>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'


Related Topics



Leave a reply



Submit