It's a compulsion; most likely a maladaptive coping skill to distract yourself from anxiety, negative thoughts, or obsessive thoughts. Learning to replace it with a positive coping skill will help extinguish the behavior. Outside of pure behaviorism, it may be beneficial to gain more insight into what is happening when you feel the urge to pull your hair. When you have an urge to pull your hair try following this acronym:
S - Stop what you are doing; sit on your hands if you need to.
T - Take a step back. This may be literal or psychological. Sometimes you need to get out of a distressing situation to think more clearly.
O - Observe (What are you feeling, thinking, what is happening, how is my body physiologically reacting).
P - Proceed (Use a replacement coping skill, manage the situational anxiety with a calmer mind, etc.)