How to Get a String After a Specific Substring

How to get a string after a specific substring?

The easiest way is probably just to split on your target word

my_string="hello python world , i'm a beginner"
print(my_string.split("world",1)[1])

split takes the word (or character) to split on and optionally a limit to the number of splits.

In this example, split on "world" and limit it to only one split.

Java: Getting a substring from a string starting after a particular character

String example = "/abc/def/ghfj.doc";
System.out.println(example.substring(example.lastIndexOf("/") + 1));

how to split string after certain character in python

This is documented here: str.rsplit()

sentence = 'b a hello b Hi'
sentence.rsplit('b', 1)

Getting a substring from a string after a particular word

yourString.substring(yourString.indexOf("no") + 3 , yourString.length());

how do I replace part of a string after a specific substring

You could use .split() with your keyword as the separator and then just concatenate the keyword and value to the first part:

url = "https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786135&planSku=Freedom%20Big%20Gig%2015GB"
keyword ="planSku="
newValue ="MyValue"
newUrl =url.split(keyword,1)[0]+keyword+newValue
print(newUrl)
# https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786135&planSku=MyValue

You could also use a regular expression substitution (re module)

import re
newUrl = re.sub(f"({keyword})(.*)",f"\\g<1>{newValue}",url)

But you will have to be careful with special characters in your keyword and newValue (which you can escape using re.escape() if need be).

Java : Getting a substring from a string after certain character

Assuming that "temp_username_current_timestamp" is not known and is expected to be different every time but you know the word or specific character that precedes what you want to extract, you should use indexOf(String str):

String input = "create table temp_username_current_timestamp other params"
String precedes = "table";
String extracted;

//Get the index of the start of the word to extract
int startIndex = input.indexOf(precedes) + precedes.length;
//Check if the word we are looking for is even there
if(startIndex > -1){
//Get the index of the next space character
int endIndex = input.indexOf(" ", startIndex);

//If there are more parameters following ignore them
if(endIndex > -1){
//Extract the parameter given the indexes found
extracted = input.substring(startIndex, endIndex);
} else {
//If we are at the end of the string just extract what remains
extracted = input.substring(startIndex);
}
}

Get everything after the dash in a string in JavaScript

How I would do this:

// function you can use:
function getSecondPart(str) {
return str.split('-')[1];
}
// use the function:
alert(getSecondPart("sometext-20202"));


Related Topics



Leave a reply



Submit