Mr Man
Mr Man

Reputation: 1588

How to remove chars in a string, and use that for another string

I am rather new at java, and I know this cant be too difficult, but I cant quite figure it out.

String xxChange = request.getParameter("XXChange");     
String yyChange = request.getParameter("YYChange");    
String zzChange = request.getParameter("ZZChange");  
String aaaChange = request.getParameter("AAChange");  

So basically I am getting these parameters and just setting them to strings. Each one of these strings has multiple numbers then two letters after it, and my question is how do I remove the letters and set it to a new string. Fyi....the number in front of the letters is on a sequence, and could grow from being 1 digit to multiple, so i dont think i can do string.Substring.

Upvotes: 1

Views: 1225

Answers (3)

dacwe
dacwe

Reputation: 43504

If you only need the last two letters:

String input = "321Ab";
String lastTwo = input.substring(input.length() - 2);

If you need both the digits and the letters use a regular expression:

Pattern p = Pattern.compile("(\\d+)(\\w{2})");
Matcher m = p.matcher("321Ab");
if (m.matches()) {
    int number = Integer.parseInt(m.group(1)); // 321
    String letters = m.group(2);               // Ab
    ...
}

Upvotes: 1

Kaj
Kaj

Reputation: 10949

You could test something like

String value = "123ABC";
System.out.println(value.replaceAll("\\d+(.*)", "$1"));

Upvotes: 1

dogbane
dogbane

Reputation: 274522

You want to remove the last two characters, so use substring like this:

String s = "123AB";
String numbers = s.substring(0, s.length() - 2);

Upvotes: 2

Related Questions