Umdurman has asked for the wisdom of the Perl Monks concerning the following question:
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Regex question
by BillKSmith (Monsignor) on Sep 17, 2023 at 04:16 UTC | |
UPDATE: Add revised code incorporating comments below.
OUTPUT:
Bill
| [reply] [d/l] [select] |
by kcott (Archbishop) on Sep 17, 2023 at 09:51 UTC | |
G'day Bill, I'd say you're on the right track creating a regex for $number and building up a more complex regex from there. Unfortunately, you're matching some things that you shouldn't.
I'd aim for a more stringent regex for $number.
The OP is somewhat unclear in that it shows an example with spaces then says spaces are removed. Stuff is also removed, whatever that refers to. There's not much we can do about that beyond requesting clarification. I'd also add ^ and $ (or equivalent) assertions to the final regex. — Ken | [reply] [d/l] [select] |
by Marshall (Canon) on Sep 17, 2023 at 13:19 UTC | |
Same as your result: updated: made capturing group | [reply] [d/l] [select] |
by Marshall (Canon) on Sep 17, 2023 at 07:13 UTC | |
In addition, for even more potential validation of this string, the number itself could be made capturing or put parens in the longer regex.
| [reply] [d/l] [select] |
by perlboy_emeritus (Scribe) on Sep 17, 2023 at 21:07 UTC | |
What does this mean: 'I strip all spaces and stuff out of the string upfront.' ??? Make whitesspace optional with \s* and add a few more tests:
| [reply] [d/l] |
|
Re: Regex question
by Umdurman (Acolyte) on Sep 17, 2023 at 09:57 UTC | |
| [reply] |
by BillKSmith (Monsignor) on Sep 17, 2023 at 21:04 UTC | |
Please note that every regex suggestion you have received is only one or two lines long. The best solution probably will be a better fit to your problem, but not much shorter.
Bill
| [reply] |
by talexb (Chancellor) on Sep 17, 2023 at 16:23 UTC | |
This looks like it works .. This assumes that you've stripped out the spaces. The regex I've used is just 'number plus operator' repeated at least once, followed by 'number'. So this should work for unsigned integers. You'd need to expand the regex for signed numbers, fractional numbers, numbers with exponents, numbers in a base higher than ten, and so forth. Update: And if you want to look for a more specific pattern (as in your original post, sorry!)
| [reply] [d/l] [select] |