0

For example, if I have these strings, is there any way I can get 123 of all these strings, or 777 or 888?

https://www.example.com/any/123/ and

https://www.example.com/any/777/123/ and

https://www.example.com/any/777/123/888

What I mean is how to match the first or second or the third last number in the string.

1
  • I don't think that's the answer I'm looking for. I want to get the penultimate nth number in the string, not just the number. Commented Aug 9, 2021 at 7:04

3 Answers 3

1

You can use capture groups to solve this as

val strList = listOf("https://www.example.com/any/777/123/888", "https://www.example.com/any/123/", "https://www.example.com/any/777/123/")
val intList = mutableListOf<Int>()
val regex = Regex("/?(\\d+)")

strList.forEach { str ->
    regex.findAll(str).forEach {
        intList.add(it.groupValues[1].toInt())
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that's exactly the answer I was looking for! Thank you! Also I would like to ask how to find the learning material for the regular content? I seem to have trouble finding them in China.
0

Assuming the digits all follow a slash and nothing intervenes,

(?<=/)\d+(?=/\d+){0}$  parses the last number
(?<=/)\d+(?=/\d+){1}$  parses the second to last number
(?<=/)\d+(?=/\d+){2}$  parses the third to last,
etc.

Comments

0

With Java, You can make use of the Pattern and Matcher class from the java.util.regex package. e.g for your case above, you want to match integers - use \d Predefined character class to match digits.

String str = "https://www.example.com/any/777/123/";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher  = pattern.matcher(str);

for(; matcher.find(); System.out.println(matcher.group()));

In the above you loop through the String finding matches, and printing each subsequent found match.

1 Comment

I don't think that's the answer I'm looking for. I want to get the penultimate nth number in the string, not just the number.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.