首页 > 解决方案 > Detecting Special Characters with Regular Expression in python?

问题描述

df

   Name
0  @#
1  R@#
2  ghj@#
3  Ray
4  *@+
5  Jack
6  Sara123#
7  ( 1234. )
8  Benjamin k 123
9  _
10 _!@#_
11 _#_&@+-
12 56#@!

Output:

 Bad_Name
0  @#
1  *@+
2  _
3  _!@#_
4  _#_&@+-

I need to detect the special character through regular expression. If a string contains any alphabet or Number then that string is valid else it will consider as bad string. I was using '^\W*$' RE, everything was working fine except when the string contains '_'( underscore) it is not treating as Bad String.

标签: regexpython-3.xpandaspython-2.7

解决方案


Use pandas.Series.str.contains:

df[~df['Name'].str.contains('[a-z0-9]', False)]

Output:

       Name
0        @#
4       *@+
9         _
10    _!@#_
11  _#_&@+-

推荐阅读