The Gav Lad
The Gav Lad

Reputation: 290

Finding a particular section of a string

I have a string and i am looking to get a particular section of it to save.

Assets/Topics/Update/filename_hj10134532.html.xls

I want to get the "hj10134532" section. How would i go about extracting that part of the string?

Any help is much appreciated.

Upvotes: 0

Views: 114

Answers (5)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

You can also do:

String input = "Assets/Topics/Update/filename_hj10134532.html.xls";
String part = input.substring(input.lastIndexOf("_") + 1, input.indexOf("."));

Upvotes: 1

LastStar007
LastStar007

Reputation: 765

Actually, there's a much simpler way than what you three have posted.

    String s="Assets/Topics/Update/filename_hj10134532.html.xls";
    return s.substring(s.indexOf("_"),s.indexOf("."));

Much more readable, and no string splitting required.

Upvotes: 0

user unknown
user unknown

Reputation: 36229

Check:

String pat = "hj10134532";
if ("Assets/Topics/Update/filename_hj10134532.html.xls".contains (pat))
    return pat;

if it contains ("hj10134532"), return it. There is no need to extract it.

Upvotes: -1

Pshemo
Pshemo

Reputation: 124225

String s="Assets/Topics/Update/filename_hj10134532.html.xls";
System.out.println(s.split("\\.")[0].split("_")[1]);
//out hj10134532

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240890

If following is the fixed format

sometext_requiredText.html.xls

then you could do it by following way

  1. Split the string by _
  2. Take the second portion (i.e. str.split("_")[1] check length of resultant array)
  3. Find the first occurrence of . using indexOf()
  4. Use substring(int, int)

Upvotes: 0

Related Questions