48

Say I want to match a "word" character (\w), but exclude "_", or match a whitespace character (\s), but exclude "\t". How can I do this?

1
  • 6
    For the benefit of others who may be using Java, .NET, XML schema, or JGSoft/RegexBuddy, there is actually a character subtraction mechanism for those flavors: stackoverflow.com/questions/3201689/… ; e.g. [a-z-[aeiou]] in .NET matches a lowercase consonant. Commented Aug 23, 2010 at 18:05

1 Answer 1

72

Use a negated class including \W or \S.

/[^\W_]/  # anything that's not a non-word character and not _
/[^\S\t]/ # anything that's not a non-space character and not \t
9
  • 11
    +1 I call this technique a double-negative.
    – Greg Bacon
    Commented Aug 23, 2010 at 15:54
  • @ThomasGuyot-Sionnest doing plus is easy; [/[:graph:]]. but / is already in graph. maybe you meant minus the / character? [^/[:^graph:]] may work for that; not sure what regex engine git is using
    – ysth
    Commented Feb 15, 2022 at 18:07
  • @ysh TBH I can't even make sense of what I wrote above - it wasn't that easy obviously but I don't exactly remember what I was struggling with. I will delete that comment. I remember I found a solution though, will have to look back at what I did... IIRC it used the cntrl class. Commented Feb 18, 2022 at 9:04
  • I finally checked... my use case was doing a git word diff where I could see just individual path component changes (to compare two build logs with slight path modification), and I'm not sure what I tried but it's very possible I wasn't even trying the right thing at first. It appears the default regex for --word-diff is [^[:space:]]+ (I see no diff using it vs plain --word-diff) and to split on paths too I just added /, so git diff '--word-diff-regex=[^[:space:]/]+' [...]. Commented Mar 2, 2022 at 4:53
  • 1
    @Unknow0059 if you are looking for }, at the end of a line that doesn't start with {, ^\s+[^{\s].*},$ or use the possessive modifier ^\s++[^{].*},$
    – ysth
    Commented Apr 26 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.