Home > Software engineering >  I want to extract only the numbers in this part of the URL.[Regular expressions]
I want to extract only the numbers in this part of the URL.[Regular expressions]

Time:11-27

I want to extract this part. But I couldn't do it well. So I need you to tell me how to do it.

Example) https://twitter.com/straw_berry0721/status/1596714080345415681?s=20&t=1nIbnSZ2YN2m5KZaOjO5GA

1596714080345415681

https://twitter.com/xxx/status/1595920708323999744

1595920708323999744

・my code (failed)

final result = _controller.text;

t = s.lastIndexOf('status'));
s.substring(t)

CodePudding user response:

One way to get this is parse it to Uri and use its path like this:

var str =
    "https://twitter.com/straw_berry0721/status/1596714080345415681?s=20&t=1nIbnSZ2YN2m5KZaOjO5GA";
Uri uri = Uri.parse(str);

print("id= ${uri.path.substring(uri.path.lastIndexOf('/')   1)}");//id= 1596714080345415681

or as @MendelG mentions in comment you can go with regex like this:

var reg = RegExp(r'status\/(\d )');
var result = reg.firstMatch(str)?.group(1);
print("result = $result"); // result = 1596714080345415681

CodePudding user response:

You could simply extract the last shown number from URLs like https://twitter.com/xxx/status/1595920708323999744 by splitting it to a List<String> then take the last element of it, like this:

String extractLastNumber(String url) {
return url.split("/").last;
}


final extractedNumber = extractLastNumber("https://twitter.com/xxx/status/1595920708323999744");

print(extractedNumber); // "1595920708323999744"
print("status: $extractedNumber"); // "status: 1595920708323999744"

Note: this will return the number as String, if you want to get it as an int number you could use the int.tryParse() method like this:

print(int.tryParse(extractedNumber)); // 1595920708323999744
  • Related