-3

I want to extract digits from the string that may contain some special characters (let's say "+-() ") but not any other characters, i.e.:

"+123 (456) 7-8" -> "1, 2, 3, 4, 5, 6, 7, 8" is extracted
"123a45" -> pattern matching fails, nothing is extracted
"1234 B" -> pattern matching fails, nothing is extracted
jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
Yurii Bodarev
  • 11
  • 1
  • 3
  • Ok, so write a regular expression that does that. – jonrsharpe Mar 05 '16 at 21:19
  • ...I took that out for a reason, see http://meta.stackexchange.com/q/2950/248731 – jonrsharpe Mar 05 '16 at 21:22
  • I've tried to play with the solution from somewhat similar question: [Regular expression to match line that doesn't contain a word?](http://stackoverflow.com/questions/406230/regular-expression-to-match-line-that-doesnt-contain-a-word) but without much luck. I can get pattern matching to fail if any letter appears but I can't extract only digits if sting also contains " -()+" characters... – Yurii Bodarev Mar 05 '16 at 21:24
  • 1
    Showing failed attempts makes downvotes less likely: People want to teach you what you've done wrong, rather than just give you code as though SO were a code writing service. – Wayne Conrad Mar 05 '16 at 22:56
  • Looking on the possible solutions below I've decided to divide task in parts: first check the string for letters via `\p{L}` and if string pass this check I can extract all digits with simple `\d` or `[0-9]` expression... – Yurii Bodarev Mar 06 '16 at 07:27

2 Answers2

1

What you want is possible with gnu sed like this:

sed -r -n '/^[-+0-9() ]+$/ {s/[^0-9]//g; s/([0-9])/\1, /g; p;}' file
  • the re ^[-+0-9() ]+$ matches your lines, that should work in other re tools
  • the part inside the { ... } creates your formated output, you need to adopt that to your tool
Lars Fischer
  • 7,817
  • 3
  • 24
  • 31
0

Free code here :

.*[^\d^+^(^)^\-^\s]+.*(?:\d)|(?:\d)(?=.*[^\d^+^(^)^\-^\s]+.*)|(\d)

Explanation:
[^\d^+^(^)^\-^\s] matches other characters except "+-() " and number

Regex Demo

Tim007
  • 2,486
  • 1
  • 9
  • 20