38

Lets say that I have a string:

a="23questions";
b="2questions3";

Now I need to parse 23 from both string. How do I extract that number or any number from a string value?

2 Answers 2

99

The following code can extract the number:

aStr = a.replaceAll(new RegExp(r'[^0-9]'),''); // '23'

You can parse it into integer using:

aInt = int.parse(aStr);
Sign up to request clarification or add additional context in comments.

1 Comment

Single Line version: int intValue = int.parse(myString.replaceAll(RegExp('[^0-9]'), ''));
13
const text = "23questions";

Step 1: Find matches using regex:

final intInStr = RegExp(r'\d+');

Step 2: Do whatever you want with the result:

void main() {
  print(intInStr.allMatches(text).map((m) => m.group(0)));
}

1 Comment

Thanks. It works but I feel like above solution will suffice and would be cleaner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.