Regex: finding a number between a range with decimals [closed] - regex

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I can not for the life of me get my head around this regex stuff after a few days of fiddling around I find myself seeking help from those wiser than I. Could any of you kind souls write me a line(s) that will find and match a number between 0.00 and x.xx? I do need the decimals however so hopefully this can be done.
I actually tried using
(\b|^)(0.00|0.01|0.02)(\b|$)
until x.xx and so forth but I couldn't fit the rest of it in because I need it to go into the 100.00+. Would anyone mind whipping something up real quick for me? : ) I would appreciate it more than you can imagine! Thanks very much for your time.
Ray.
Edit:
So i forgot to explain what I'm trying to achieve here, I'm using it in conjunction with a Chrome addon called Page Monitor (life saver folks try it out when you have time to kill!) which pings every time an a website updates, this also works for shares but I'm trying to make it only alert me when the price drops below a certain point eg $4.99 per share, will (\b|^)([0-9]+\.[0-9]{2})(\b|$) and ([0-9]+.[0-9]+) suffice?

Why isn't this good enough: ([0-9]+\.[0-9]+) ?
If you can give an example of input and what is the output you expect, it would be easier to write a regex.
Updated: $ sign is a reserved character in RegEx, it means end-of-line, so you need to use \$, if you plan on using it.
So your regex would be \$([0-9]+\.[0-9]+), this would capture your $4.99 and $5.10, etc, not just $4.99
Regexs in general are good at capturing data, less at analyzing it, but if you must, you can do this to determine when the price goes below $4.99 =>
\$(([0-3]\.[0-9]+)|(4\.[0-8][0-9])|(4\.9[0-8]))
It should be obvious that its a waste of resource :)

Didn't provide enough info but this will match if the number is the entire value or if it is within a larger string and the number is not withing something else like "foo8.9bar". This will match any 1 or more digit number on the left side of the decimal and exactly 2 numbers on the right side
(\b|^)([0-9]+\.[0-9]{2})(\b|$)

(\b|^) and (\b|$) are redundant because \b implies ^ and $.

this regex: (\d+\.\d{2}) should do it.

Related

Conditional Regex for Percentage based values [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I've never been very good at regex, but I really need to grab the percentage information from these log entries; however, the warn/critical message moves around depending on where the warning was located in either the In or the Out utilization. I just can't figure out the regex. Here are two example entries that show both in and out issues:
["XXXXXXX"], (up), MAC: XX:XX:XX:XX:XX:XX, Speed: 2 GBit/s, In: 0 Bit/s (0%), Out: 6.53 GBit/s (warn/crit at 1.6 GBit/s/1.8 GBit/s) (326.45%)(!!)
["XXXXXXX"], (up), MAC: XX:XX:XX:XX:XX:XX, Speed: 2 GBit/s, In: 0 Bit/s (warn/crit at 1.6 GBit/s/1.8 GBit/s) (95.45%), Out: 6.53 GBit/s (32.00%)(!!)
Ultimately I need to use capture groups to capture both the in and out utilization percentage. But every regex I try only finds a single percentage. Help on this would be greatly appreciated. Thanks in advance.
EDIT SHOWING EXPECTED RESULT:
for each line the regex capture groups would identify in and out so the program can see both the in and out utilization. The program is expecting a key value pair from every log entry like the following:
IN:0% OUT:326.45%
IN:95.45% OUT:32.00%
Do you need something like this?
In:.+\(([0-9\.]+%)\).+Out:.+\(([0-9\.]+%)
If you just need to pull out values with percentage information, then it can help
https://regex101.com/r/B9pZeO/1

Questions about using regular expressions [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm trying to learn more about regex and I'm running into a block
my current query:
function telephoneCheck(str) {
return str.match(/[0-9]{3}[-][0-9]{3}[-][0-9]{4}/g)? true : false
}
This will only work for a specific inputs such as "555-555-5555", but for other inputs such as "1 (555) 555-5555" it will not. I'm at a loss on how to query for optional characters and whitespace. Moreover bracket handling is odd and I've found some crazy queries such as /(\d+-)\1\d{4}/g but I have no idea what its doing and I don't want to use code I don't understand.
Can someone show me a query that solves for "1 (555) 555-5555" where the first two characters (the one and space) are optional inputs?
These are inputs that the regex should be able to handle:
"1 (555) 555-5555"
"1(555)555-5555"
"1 555-555-5555"
"555-555-5555"
"(555)555-5555"
"5555555555"
I found a solution
regex: function telephoneCheck(str) {
var regex = /^(1\s?)?(\(\d{3}\)|\d{3})[\s\-]?\d{3}[\s\-]?\d{4}$/;
return regex.test(str);
}
telephoneCheck("555-555-5555");
But I have no idea whats going on in here. If someone could explain whats happening I'd be happy to give you the answer for this posted question :)
You have be wary of trying to be all things within regex and question why the data is so varied in the first place.
If you are just parsing a bunch of what you are thinking should be phone numbers for example and notice a lot of different formats it might actually be more readable to use logic.
There is probably a really clever way of doing the above but I tend to be a bit more brute force with regex until I need more.
The below combines both patterns in to one regex expression. You use the | separator to say or. Also if your strings are exactly as you say, you should to use the ^ (starts with) and $ ends with to ensure you don't get false positives.
var pattern = /^[0-9] \([0-9]{3}\) [0-9]{3}-[0-9]{4}$|^[0-9]{3}[-][0-9]{3}[-][0-9]{4}$/
pattern.test('555-555-5555') //true
pattern.test('1 (555) 555-5555') // true
pattern.test('(555) 555-5555') // false
And as I say if you have lots of different formats in one. Question why, is there a way to clean things up first. Then perhaps use logic and separate statements.
var parensPattern = /^[0-9] \([0-9]{3}\) [0-9]{3}-[0-9]{4}$/
var noParensPattern = /^[0-9]{3}[-][0-9]{3}[-][0-9]{4}$/
if(parensPattern.test('1 (555) 555-5555')) {
// do something
} else if (noParensPattern.test('555-555-5555)) {
// do something
}
Check out http://regex101.com, it is a great resource.

RegExp Remove content outside of commas [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
Alright, so I have a database where you can get information from that'll show off in this kind of way:
ID, Display name, Likes Cake, Likes Coffee, Likes Dogs
So if you get the information, it would show something a little like to this:
1,anonymous,1,0,1
Now it's not very popular so I would like to show the people who has answered this so I would like the "1,!anonymous!,1,0,1" (anything outside the !'s) gone. I looked around and found a RegExp code that would remove stuff outside quotes, but it's rather hard and I'm rather impatient to put all the display names in quotes.
So if there was a RegExp that would erase the numbers so I could put the usernames up, would be delicious.
Well, you could do something like this:
Replae '^[^,]+([^,]+).*' With '$1'
How it looks exactly in your language may vary, of course.
But in your case this looks like CSV, so isn't parsing the CSV file easier in that case? E.g. in PowerShell you could do
Import-Csv foo.csv | select 'Display name'
and likewise for other languages that have such parsing built-in somewhere. Besides, most other options may break depending on the input because fields in CSV may contain commas too which breaks both above regex and a naïve splitting method.
You can split the database result string and then get the relevant array index.
string dbString = "1,anonymous,1,0,1";
string username = dbString.Split(',')[1];
//value of username will be "anonymous"

I'm going to be teaching a few developers regular expressions - what are some good homework problems? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm thinking of presenting questions in the form of "here is your input: [foo], here are the capture groups/results: [bar]" (and maybe writing a small script to test their answers for my results).
What are some good regex questions to ask? I need everything from beginner questions like "validate a 4 digit number" to "extract postal codes from addresses".
A few that I can think off the top of my head:
Phone numbers in any format e.g. 555-5555, 555 55 55 55, (555) 555-555 etc.
Remove all html tags from text.
Match social security number (Finnish one is easy;)
All IP addresses
IP addresses with shorthand netmask (xx.xx.xx.xx/yy)
There's a bunch of examples of various regular expression techniques over at www.regular-expressions.info - everything for simple literal matching to backreferences and lookahead.
To keep things a bit more interesting than the usual email/phone/url stuff, try looking for more original exercises. Avoid boredom.
For example, have a look at the Forsysth-Edwards Notation which is used for describing a particular board position of a chess game.
Have your students validate and extract all the bits of information from a string like this:
rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2
Additionaly, have a look at algebraic chess notation, used to describe moves. Extract chess moves out of a piece of text (and make them bold).
1. e4 e5 2. Nf3 Black now defends his pawn 2...Nc6 3. Bb5 Black threatens c4
Validate phone numbers (extract area code + rest of number with grouping) (Assuming US phone number, otherwise generalize for you style)
Play around with validating email address (probably want to tell the students that this is hugely complicated regular expression but for simple ones it is pretty straight forward)
regexplib.com has a good library you can search through for examples.
H0w about extract first name, middle name, last name, personal suffix (Jr., III, etc.) from a format like:
Smith III, John Paul
How about Reg Ex to remove line breaks and tabs from the input
I would start with the common ones:
validate email
validate phone number
separate the parts of a URL
Be cruel. Tell them parse HTML.
RegEx match open tags except XHTML self-contained tags
Are you teaching them theory of finite automata as well?
Here is a good one: parse the addresses of churches correctly from this badly structured format (copy and paste it as text first)
http://www.churchangel.com/WEBNY/newhart.htm
I'm a fan of parsing date strings. Define a few common data formats, as well as time and date-time formats. These are often good exercises because some dates are simple mixes of digits and punctuation. There's a limited degree of freedom in parsing dates.
Just to throw them for a loop, why not reword a question or two to suggest that they write a regular expression to generate data fitting a specific pattern like email addresses, phone numbers, etc.? It's the same thing as validating, but can help them get out of the mindset that regex is just for validation (whereas the data generation tool in visual studio uses regex to randomly generate data).
Rather than teaching examples based from the data set, I would do examples from the perspective of the rule set to get basics across. Give them simple examples to solve that leads them to use ONE of several basic groupings in each solution. Then have a couple of "compound" regex's at the end.
Simple:
s/abc/def/
Spinners and special characters:
s/a\s*b/abc/
Grouping:
s/[abc]/def/
Backreference:
s/ab(c)/def$1/
Anchors:
s/^fred/wilma/
s/$rubble/and betty/
Modifiers:
s/Abcd/def/gi
After this, I would give a few examples illustrating the pitfalls of trying to match html tags or other strings that shouldn't be done with regex's to show the limitations.
Try to think of some tests that don't include ones that can be found with Google.
Asking a email validator should pose no trouble finding..
Try something like a 5 proof test.
Input 5 digit. Sum up each digit must be dividable by five: 12345 = 1+2+3+4+5 = 15 / 5 = 3(.0)

I'm looking for an application/text editor that [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
can best help me systematically modify the "replace" field of a regex search as it encounters each match.
For example, I have an xml file that needs the phrase "id = $number" inserted at regular points in the text, and basically, $number++ each time the regex matches (id = 1, id = 2, etc) until the end of the file.
I know I could just write a bash/perl/python script or some such, but I'd like it to be at least moderately user-friendly so I could teach my intelligent (but less technically-inclined) workers how to use it and make their own modifications. Regexing is not a problem for them.
The closest I've come so far is Notepad++'s Column Editor and 'increase [number] by' function, but with this I have to write a separate regex to align everything, add the increments, and then write another to put it back. Unfortunately, I need to use this function on too many different types of files and 'replace's to make macros feasible.
Ideally, the program would also be available for both Windows & Linux (WINE is acceptable but native is much preferred), and have a 'VI/VIM input' option (if it's a text editor), but these are of secondary importance.
Of course, it'd be nice if there is an OSS solution, and I'd be glad to donate $20-$50 to the developer(s) if it provides the solution I'm looking for.
Apologies for the length, and thanks so much for your help!
emacs (version 22 and later) can do what you're looking for. See Steve Yegge's blog for a really interesting read about it. I think this should work:
M-x replace-regexp
Replace regexp: insert pattern regexp here
Replace regexp with: id = \#
\# is a special metacharacter that gets replaced by the total number of replacements that have occurred so far, starting from 0. If you want the list to start from 1 instead of 0, use the following replacement string:
id = \,(1+ \#)
JEdit can probably help you:
http://www.jedit.org/
you can do all kinds of regex and even bean result based replacing with it.
UltraEdit32 is great and I believe it has the features you need. There is a free 30-day download so you can make sure. :)
I know you want an app available on Windows/Linux, but there's another solution on Mac : TextWrangler, and it's free.
Take a look at UltraEdit32. It's very good. Not free, but available in Windows, Linux and Mac platforms. It has regex based search & replace.
This script should let you do what you want in Vim.
Vim functions can do the incrementing number trick and aren't too hard to write. For example the Vim wiki says how to do this. See also :h sub-replace-\=.
function! Counter()
let i = g:c
let g:c = g:c + 1
return i
endfunction
:let c=1|%s/<\w\+\zs/\=' id="' . Counter() . '"'/g
We've probably left user-friendliness long behind at this point but Vim's Ruby support can do this kind of thing easily too:
:ruby c=0
:rubydo $_.gsub!(/<\w+/){|m| c += 1; m + ' id="' + c.to_s + '"'}
Or Perl:
:perl $c=1
:perldo s/<\w+/$& . ' id="' . $c++ . '"'/eg
To me, this sounds like it might be a job for awk, rather than a job for an editor.