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"
Splitting on last delimiter in Python string?
Use .rsplit()
or .rpartition()
instead:
s.rsplit(',', 1)
s.rpartition(',')
str.rsplit()
lets you specify how many times to split, while str.rpartition()
only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case.
Demo:
>>> s = "a,b,c,d"
>>> s.rsplit(',', 1)
['a,b,c', 'd']
>>> s.rsplit(',', 2)
['a,b', 'c', 'd']
>>> s.rpartition(',')
('a,b,c', ',', 'd')
Both methods start splitting from the right-hand-side of the string; by giving str.rsplit()
a maximum as the second argument, you get to split just the right-hand-most occurrences.
If you only need the last element, but there is a chance that the delimiter is not present in the input string or is the very last character in the input, use the following expressions:
# last element, or the original if no `,` is present or is the last character
s.rsplit(',', 1)[-1] or s
s.rpartition(',')[-1] or s
If you need the delimiter gone even when it is the last character, I'd use:
def last(string, delimiter):
"""Return the last element from string, after the delimiter
If string ends in the delimiter or the delimiter is absent,
returns the original string without the delimiter.
"""
prefix, delim, last = string.rpartition(delimiter)
return last if (delim and last) else prefix
This uses the fact that string.rpartition()
returns the delimiter as the second argument only if it was present, and an empty string otherwise.
Split string into two parts only
You could use a,b = split(' ', 1)
.
The second argument 1
is the maximum number of splits that would be done.
s = 'abcd efgh hijk'
a,b = s.split(' ', 1)
print(a) #abcd
print(b) #efgh hijk
For more information on the string split function, see str.split
in the manual.
How to split a string into 2 at the last occurrence of an underscore character
You can use lastIndexOf
on String
which returns you the index of the last occurrence of a chain of caracters.
String thing = "132131_12313_1321_312";
int index = thing.lastIndexOf("_");
String yourCuttedString = thing.substring(0, index);
It returns -1
if the occurrence is not found in the String.
Split string on the last occurrence of some character
It might be easier to just assume that files which end with a dot followed by alphanumeric characters have extensions.
int p=filePath.lastIndexOf(".");
String e=filePath.substring(p+1);
if( p==-1 || !e.matches("\\w+") ){/* file has no extension */}
else{ /* file has extension e */ }
See the Java docs for regular expression patterns. Remember to escape the backslash because the pattern string needs the backslash.
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 in to 2 based on last occurrence of a separator
Use rpartition(s)
. It does exactly that.
You can also use rsplit(s, 1)
.
How do I Split string only at last occurrence of special character and use both sides after split
You can use String.Substring
with String.LastIndexOf
:
string str = "SQL injection - Wikipedia, the free encyclopedia - Mozilla Firefox";
int lastIndex = str.LastIndexOf('-');
if (lastIndex + 1 < str.Length)
{
string firstPart = str.Substring(0, lastIndex);
string secondPart = str.Substring(lastIndex + 1);
}
Create a extension method (or a simple method) to perform that operation and also add some error checking for lastIndex
.
EDIT:
If you want to split on " - "
(space-space) then use following to calculate lastIndex
string str = "FirstPart - Mozzila Firefox-somethingWithoutSpace";
string delimiter = " - ";
int lastIndex = str.LastIndexOf(delimiter);
if (lastIndex + delimiter.Length < str.Length)
{
string firstPart = str.Substring(0, lastIndex);
string secondPart = str.Substring(lastIndex + delimiter.Length);
}
So for string like:
"FirstPart - Mozzila Firefox-somethingWithoutSpace"
Output would be:
FirstPart
Mozzila Firefox-somethingWithoutSpace
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 at last occurrence of character then join
You can use .attr( attributeName, function )
with callback function to update the attribute value of respective element. To add the string -fx
in the src attribute, String#lastIndexOf
and String#substring
can be used.
// Get the src attribute value of image one by one$('img').attr('src', function(i, src) { // Get the index of the last . var lastIndex = src.lastIndexOf('.');
// Add the string before the last . // Return updated string, this will update the src attribute value return src.substr(0, lastIndex) + '-fx' + src.substr(lastIndex);});
img { height: 100px; width: 100px; background: red;}img[src$="-fx.jpg"] { background: blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><img src="extension.jpg" /><img src="ext.ension.jpg" />
Related Topics
Rails 4 User Roles and Permissions
How to Replace the Last Occurrence of a Substring in Ruby
How Does MACports Install Packages? How to Activate a Ruby Installation Done via MACports
Detect Browser Language in Rails
How to Parse Consecutive Tags with Nokogiri
How to Change the Zone Offset for a Time in Ruby on Rails
Rails Console Default Environment
How to Validate a Specific Attribute on an Activerecord Without Instantiating an Object First
How to Expire a View Cached Fragment from Console
Missing a Template for This Request Format and Variant
How to Instruct Capistrano 3 to Load My Shell Environment Variables Set at Remote Host
How to Check If There's a Nil Set or Not in an Array
Ruby: How to Generate CSV Files That Has Excel-Friendly Encoding
How to Assign Multiple Values to a Hash Key
Rails: Pg::Insufficientprivilege: Error: Permission Denied for Relation Schema_Migrations