0

I have several lines of text such as:

"you current have 194764bleh notifications"
"you current have 32545444bleh notifications"
"you current have 8132bleh notifications"
"you current have 93bleh notifications"

What's the best way to get the integers from the text ?

Currently using line.split twice, once for "have" and then once for "bleh".
It seems really inefficient doing that just to get the integers.

Are there any better ways to do that?

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
Walter
  • 21
  • 1
  • That's perfectly fine (IMHO), splitting by substring is faster than using regex. – Nir Alfasi Jun 01 '15 at 02:52
  • @alfasin For some useless definition of 'faster'. A regular expression is more clear and more maintainable for this particular ad hoc task. The few 'wasted' CPU cycles are irrelevant; micro-benchmarks need not apply. – user2864740 Jun 01 '15 at 02:53
  • 1
    It already has a solution here http://stackoverflow.com/questions/4030928/extract-digits-from-a-string-in-java – aakansha Jun 01 '15 at 02:58
  • @user2864740 I guess that it depends on how many times this method will be called. Two splits vs. one regex seems fair to me (I wouldn't be irritated to find either of them in the code that I maintain). If it was a tradeoff of 10 splits vs. one regex I would definitely agree with you, but in this case - I'm good with both. – Nir Alfasi Jun 01 '15 at 03:01

3 Answers3

2

E.g.

String str = "you current have 194764bleh notifications";
str = str.replaceAll("\\D", ""); // Replace all non-digits

Using regex to take away all the non-digits will be an option,
it will also not restrict you to having 'have' & 'bleh' wrap the numbers.

Not entirely sure about the efficiency as compared to using split though.

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
  • Efficiency is likely irrelevant (this will be fast). It does change the semantics, such that it would accept `"Hello 12 World 34"`, but that was noted - if these relaxations are OK then I'd use something similar. – user2864740 Jun 01 '15 at 02:56
0

You can get a substring from above line and then convert it to int.

String strVal1 = line2.substring(17, line2.indexOf("bleh"));
int intVal1 = Integer.parseInt(strVal1);

I have considered the string format will be same. If not you can change the start index to the index of "have ".

umuieme
  • 729
  • 6
  • 20
0

Recently I like to use regular expression to extract what I need in a string. So I would like to use the method as below:

String a = "you current have 194764bleh notifications";

Pattern numPattern = Pattern.compile("(\\d+)");
Matcher theMather = numPattern.matcher(a);
if(theMather.find())
{
    System.out.println(theMather.group(1));
}

I have tested the code. Wish it is helpful.

Javakid
  • 357
  • 1
  • 10