Why grep regex doesn't find cases?

I have tried two regexes for grep. The first is simple and can find both switch and case words. The second fails for cases:

$ grep -nE "switch|case" ./a_switches.txt
1:		switch ($mode)
3:			case 'overview':
98:					switch ($action)
100:						case 'banuser':
101:						case 'banemail':
102:						case 'banip':
126:							switch ($action)
128:								case 'banuser':
133:								case 'banemail':
138:								case 'banip':
166:						case 'reactivate':
251:						case 'active':
317:						case 'delsig':
343:						case 'delavatar':
363:						case 'delposts':
386:						case 'delattach':
411:						case 'deloutbox':
461:						case 'moveposts':
622:						case 'leave_nr':
923:					switch ($user_row['user_inactive_reason'])
925:						case INACTIVE_REGISTER:
929:						case INACTIVE_PROFILE:
933:						case INACTIVE_MANUAL:
937:						case INACTIVE_REMIND:
977:					'U_SWITCH_PERMISSIONS'	=> ($auth->acl_get('a_switchperm') && $user->data['user_id'] != $user_row['user_id']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", "mode=switch_perm&u={$user_row['user_id']}&hash=" . generate_link_hash('switchperm')) : '',
993:			case 'feedback':
1107:			case 'warnings':
1243:			case 'profile':
1407:			case 'prefs':
1680:			case 'avatar':
1816:			case 'rank':
1857:			case 'sig':
1988:			case 'attach':
2144:			case 'groups':
2170:				switch ($action)
2172:					case 'demote':
2173:					case 'promote':
2174:					case 'default':
2193:					case 'delete':
2232:					case 'approve':
2368:			case 'perm':
$ grep -nE "\bswitch\s*\(|\bcase:\s*'[\w_]" ./a_switches.txt
1:		switch ($mode)
98:					switch ($action)
126:							switch ($action)
923:					switch ($user_row['user_inactive_reason'])
2170:				switch ($action)

Can you please help to fix the second one, and explain what's the problem here.

There is no string case: in your input sample.

Also \w is not defined within a [ ] unless in PCRE (grep -P)

An untested attempt:

grep -nE "\bswitch\s*\(|\bcase\s*([_[:alnum:]]+|([\"']).*\2)\s*:" ./a_switches.txt
1 Like

Oh my fault. I expected ":" before the string but it is like "case 'overview':". I If use -P I got error some collision of samples/patterns or like that. so [:alnum:] is the solution instead of \w

try

grep -nE '^[[:blank:]]?+(switch|case)'