-2

I'm in the process of modifying an existing regex to match Credit Card numbers. Sometimes such numbers are presented as follows that separate the number chunks with spaces or dashes as follows;

3756-4564-2323-3435
3756 6432 3233 435

These types of matches should be preprocessed to remove those special characters. Usually the number chunks are of 3 to 4 digits.

thanks

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
user3148655
  • 111
  • 2
  • 1
    [What have you tried?](http://mattgemmell.com/what-have-you-tried/)? This is very straightforward. – elixenide Jun 05 '16 at 02:24
  • So, you would want to use Regex substitution then? Something simple like `(\d{4})[ -](\(\d{4})[ -](\d{4})[ -](\d{3,4})` for the match and `\1\2\3\4` for the replace should do the trick. – micsthepick Jun 05 '16 at 02:29
  • Im sorry Ed, Im not good at regex. Appreciate if you could help – user3148655 Jun 05 '16 at 02:30
  • thanks micsthepick. I have modified your suggestion to comply with BASH, ([0-9]{4})[ -]([0-9]{4})[ -]([0-9]{4})[ -]([0-9]{3,4}) – user3148655 Jun 05 '16 at 02:35

2 Answers2

1

In bash you could remove anything that is not numbers with:

$ var="3756-4564-2323-3435"
$ echo "${var//[^0-9]}"
3756456423233435
0

As @Ed mentioned, you should try to solve things on your own before asking for the solution. Otherwise, shouldn't (\d{4})[ -](\(\d{4})[ -](\d{4})[ -](\d{3,4}) match the number correctly, storing each part in capturing groups 1-4?

If you need to handle numbers that do not already have separators, just make them optional with the ? qualifier: (\d{4})[ -]?(\(\d{4})[ -]?(\d{4})[ -]?(\d{3,4}).

micsthepick
  • 562
  • 7
  • 23
  • Thanks @mic. My bad. i have used sed to replace `sed -E 's/([0-9]{4})[ -]([0-9]{4})[ -]([0-9]{4})[ -]([0-9]{3,4})/\1\2\3\4/g' *` but how use it to repalce all the matches within a file – user3148655 Jun 05 '16 at 02:58
  • @user3148655 "Have you tried" the global flag, `g`, `sed -i ‘s/([0-9]{4})[ -]([0-9]{4})[ -]([0-9]{4})[ -]([0-9]{3,4})/\1\2\3\4/g’ file.txt` should work fine. – micsthepick Jun 05 '16 at 03:00
  • yes. it gives me this error. `sed: -e expression #1, char 67: invalid reference \4 on `s' command's RHS` – user3148655 Jun 05 '16 at 03:03
  • @user3148655 `sed -E 's/([0-9]{4})[ -]([0-9]{4})[ -]([0-9]{4})[ -]([0-9]{3,4})/\1\2\3\4/g' a.txt` works fine for me. – micsthepick Jun 05 '16 at 03:16
  • it works. but it does not replace the text in the file, only displays. – user3148655 Jun 05 '16 at 03:25
  • so then use: `sed -E 's/([0-9]{4})[ -]([0-9]{4})[ -]([0-9]{4})[ -]([0-9]{3,4})/\1\2\3\4/g' a.txt > a.txt`, you need to use the basic BASH operator; `>` which should "redirect" the output to the file specified. – micsthepick Jun 05 '16 at 03:38