Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all characters before a specific character in Java?

Tags:

I have a string and I'm getting value through a html form so when I get the value it comes in a URL so I want to remove all the characters before the specific charater which is = and I also want to remove this character. I only want to save the value that comes after = because I need to fetch that value from the variable..

EDIT : I need to remove the = too since I'm trying to get the characters/value in string after it...

like image 266
Shariq Musharaf Avatar asked Dec 01 '16 12:12

Shariq Musharaf


People also ask

How do I remove all characters from a string after a specific character?

Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .

How do you replace a string before a specific character in Java?

replaceFirst(String regex, String replacement) : Replaces the first substring of this string that matches the given regular expression with the given replacement. replaceAll(String regex, String replacement) : Replaces each substring of this string that matches the given regular expression with the given replacement.

How do you cut a string out of a certain character in Java?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.


2 Answers

You can use .substring():

String s = "the text=text"; String s1 = s.substring(s.indexOf("=") + 1); s1.trim(); 

then s1 contains everything after = in the original string.

s1.trim()

.trim() removes spaces before the first character (which isn't a whitespace, such as letters, numbers etc.) of a string (leading spaces) and also removes spaces after the last character (trailing spaces).

like image 75
ItamarG3 Avatar answered Oct 05 '22 06:10

ItamarG3


While there are many answers. Here is a regex example

String test = "eo21jüdjüqw=realString"; test = test.replaceAll(".+=", ""); System.out.println(test);  // prints realString 

Explanation:

.+ matches any character (except for line terminators)
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
= matches the character = literally (case sensitive)

This is also a shady copy paste from https://regex101.com/ where you can try regex out.

like image 24
Murat Karagöz Avatar answered Oct 05 '22 06:10

Murat Karagöz