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.

Mab
  • 412
  • 3
  • 12
pnkj
  • 406
  • 5
  • 17
  • 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. – pnkj Aug 09 '21 at 07:04

3 Answers3

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())
    }
}
mightyWOZ
  • 7,946
  • 3
  • 29
  • 46
  • 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. – pnkj Aug 09 '21 at 07:08
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.

Mab
  • 412
  • 3
  • 12
  • 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. – pnkj Aug 09 '21 at 07:06
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.
Chris Maurer
  • 2,339
  • 1
  • 9
  • 8