Home > Software engineering >  How to use lastindexof function to find index of "|"
How to use lastindexof function to find index of "|"

Time:10-27

my string is as follows :-

acc = "123456|"

I want to extract "123456" i.e., need to exclude "|" .

One way is to use replace but, I don't want to use replace hence was trying in following way:-

 acc.substring(0,acc.lastIndexOf(Pattern.quote("|")))
 acc.substring(0,acc.lastIndexOf("\\|"))
 acc.substring(0,acc.lastIndexOf("|"))

In all the three cases it was returning -1. So, how to find the index of "|" ????

CodePudding user response:

The last option is correct. As I Already tested

https://rextester.com/NTZ17950

String acc = "123456|";
System.out.println(acc.substring(0,acc.lastIndexOf("|")));

CodePudding user response:

If you have an input string with a single number, possibly containing other content, the most straightforward approach might be to use a regex replacement:

String acc = "123456|";
String num = acc.replaceAll("\\D ", "");
System.out.println(num);  // 123456
  •  Tags:  
  • java
  • Related