Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want a regular expression that give me e.g. $1000 from any given string
string may contain

text $1000 text
Or
text $1,000 text
or
text 1,000$ text
or
text 1000$ text
or
text$1000 text

or any combination of text and $1000/$10,000

$ may appear more than once in a string but i just want $1000 or $+number

any suggestions or solution please
Posted

This regex will do it:

(\$\d+(,\d{3})*|\d+(,\d{3})*\$)


Explanation:
- You need to escape the dollar sign, since it's a special character in regex
- The main part of the regex is any number of digits possibly followed by combinations of comma and three digit sections
- There's an alternation around the whole thing, guaranteeing a $ either at the beginning or the end
 
Share this answer
 
v4
Comments
Hammad 31-Jan-14 8:43am    
No success it reads all numbers
I give you an example string "1965 Ford Falcon Wagon $$$4000" and i only need to extract $4000 from it $4000 may also be like $4,000 but your answer just extract 1965 any solution...?
Brian A Stephens 31-Jan-14 9:20am    
I see that you may have two possible problems. You need to define the regex using a verbatim string literal, so the backslashes aren't interpreted in the string itself: string pattern = @"(\$\d+(,\d{3})*|\d+(,\d{3})*\$)". Secondly, if you are using Regex.Matches, it should return ALL matches, not just the first.
Hammad 31-Jan-14 11:23am    
thanks buddy! it works..
(?<=.*\$)\d+,?\d+(?=.*)|(?<=.*)\d+,?\d+(?=\$)

You will have to use replace method to remove the commas if any. replace method[^]

The explanation of the regex pattern:

. matches any character except newline
* means zero or more times
\$ refer to a $ sign
So, .*\$ matches zero or more characters followed by a $ sign
(?<=.*\$) will match a position immediately followed by zero or more characters followed by a $ sign

\d matches any digit
+ means one or more times
So, \d+ matches one or more digits

? means zero or one time
So, ,? matches zero or one comma

(?=.*) will match a position immediately precede a zero or more characters

Putting them together you get (?<=.*\$)\d+,?\d+(?=.*) that matches any number preceded by $ sign.

| means OR

(?<=.*)\d+,?\d+(?=\$) matches any number followed by $ sign.
 
Share this answer
 
v5
Comments
Hammad 31-Jan-14 11:31am    
thanks Peter it works great but can you explain it i don't know much about regular expressions
Peter Leow 31-Jan-14 21:12pm    
You got it, I have added the explanation in the solution.
Hammad 1-Feb-14 15:05pm    
thanks peter you saved my day

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900