1

I am looking for a regular expression in Ruby to capture a sentence that has any sort of number in it.

For instance, I need to capture all of the following:

  • "5 different ways to do it"
  • "2 x 2 is certainly 4"
  • "there are 15 different things"
  • "Try to get to 10"

I only want to capture sentences with a number within, but that has nothing else before or after the number. I don't want to include things like:

  • "$2 billion dollars"
  • "The 5x effect"

It has to be just a sequence for 1 or more numbers at the beginning, middle, or end of a sentence.

Thanks.

6
  • regular-expression.info Commented Mar 16, 2014 at 2:23
  • What about `3, ~3, !3, $3, %3, ^3, ..., 3., 3,, 3?, ... and a lot more; are they to be captured? You haven't made clear at all your conditions. Commented Mar 16, 2014 at 2:25
  • What if it has both: "The 5 5x effects" Commented Mar 16, 2014 at 2:32
  • Sorry - I realize there are a potential lot of conditions. Commented Mar 16, 2014 at 2:44
  • @sawa - nothing like the sorts - no special characters around the number. Commented Mar 16, 2014 at 2:45

2 Answers 2

1

You probably want something like:

/^.*(?<!\S)\d+(?!\S).*$/

Which will match a number and "look-around" for a non-space.

Sign up to request clarification or add additional context in comments.

1 Comment

This seems to work very nicely. Thanks very much! I will tweak as needed, if need be. Just needed a head start here.
0

This

(s =~ /(^|\s)\d+(\s|$)/) ? s : nil

will return the string s if it contains at least one non-negative integer, that is:

  • the entire string,
  • at the beginning of the string followed by a whitespace character,
  • at the end the string preceded by a whitespace character, or
  • is both preceded and followed by a whitespace character.

4 Comments

This doesn't capture the string.
Thanks, @ pguardiario. Fixed.
Np. \b doesn't work because there's a \b between $ and 2 in $2
pg, not going well for me this evening. I rolled back to what I started with, adjusted to return the string if the regex matches. Thanks.

Your Answer

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