0

could someone help me with my regular expression in php?

this is my regex:

(?:\d*(\,)\d*)(\,\d*)?(\,\d*)?(\,\d*)?

this is my testdata:

1~ 2,906,730 RX

1-.’ 2,733,975 Rx

/ 132,882 RX mu uuu Au

'2(*__/ 182 rX ....212

I need to match the numbers before 'RX' or 'rX' or 'Rx'. with above code the numbers in the last line don't get matched because it misses a ','.

I believe there is a better way to do this. right now my regular expression doesn't even check if its followed by 'RX'.

any help would greatly be appreciated! solution may be posted in php code.

2
  • 1
    You don't need to escape comma. Commented Apr 10, 2014 at 1:39
  • Matching any combination of numbers and dots (simplest approach) could be done with [\d.]+ and a space can be noted literally or with \s and a literal RX at the end would work with the /i case-insensitive flag. Commented Apr 10, 2014 at 1:43

1 Answer 1

3

I think this will do it:

preg_match('/\d{1,3}(?:,\d{3}+)*(?= rx)/i', $data, $match);

?= is a positive lookahead -- it requires the previous regexp to be followed by this group. And i makes the regexp case-insensitive, so it will match RX, rx, or any combination.

DEMO

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

6 Comments

If the comma is to be used as the thousands separator, a better regular expression will be "/\\d{1,3}(?:,\\d{3})*(?= rx)/i" but I admit that the author of the question has left it unclear.
@SharanyaDutta Thx. You don't need to double the backslashes inside single-quoted strings.
I’ve written the regular expression as a double-quoted string. You may consider using preg_match_all instead of preg_match so the author of the question gets all the matching values, not only the first one.
I don't know whether the OP is processing the input data all at once or line by line. It seems like his main problem was getting the regexp right, not the PHP syntax for using it.
You can remove the commas after matching with str_replace().
|

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.