liveBook · Manning

Non-word character

As explained in Learn PowerShell in a Month of Lunches: Fourth Edition, Covers Windows, Linux, and macOS

A nonword character is a regular-expression character that is not a letter, digit, or underscore, including whitespace and punctuation.

A non-word character is anything that is not a letter, number, or underscore. In regular expressions, \W matches these characters, including whitespace and punctuation; its meaning is the opposite of \w. section 21.2

Use non-word characters when a pattern must cross separators or include symbols:

  • [\w\W]+ matches one or more word or non-word characters—in practice, any characters. section 21.4
  • Including \W prevents a pattern from stopping at punctuation such as a hyphen, which \w does not match. section 21.4
  • PowerShell regex matching is case-sensitive for \w and \W, even though ordinary matching is case-insensitive by default. section 21.2

Match a browser request in IIS logs

The pattern 10\.0;[\w\W]+\+Gecko matches Windows NT 10.0 user-agent text, allows any characters between the semicolon and +Gecko, and treats the plus sign literally. Use it with Select-String to locate matching log lines. section 21.4

PS C:\logfiles> get-childitem -filter *.log -recurse | 
Select-string -pattern "10\.0;[\w\W]+\+Gecko"
W3SVC1\u_ex120420.log:14:2012-04-20 21:45:04 10.211.55.30 GET /MyApp1/Testpage.asp 
    - 80 - 10.211.55.29 Mozilla/5.0+(Windows+NT+10.0;+WOW64;+rv:11.0)+Gecko/20100101+Firefox/11.0 200 0 0 1125
W3SVC1\u_ex120420.log:15:2012-04-20 21:45:04 10.211.55.30 GET /TestPage.asp 
    - 80 - 10.211.55.29 Mozilla/5.0+(Windows+NT+10.0;+WOW64;+rv:11.0)+Gecko/20100101+Firefox/11.0 200 0 0 1 109

This output shows Select-String locating IIS log entries with the 10.0;[\w\W]+\+Gecko pattern. section 21.4

How Learn PowerShell in a Month of Lunches: Fourth Edition, Covers Windows, Linux, and macOS covers it

How deep it goes
Defines \W through contrasts with \w and demonstrates combined character classes, but does not develop regex internals.
Examples
Uses IIS user-agent strings and Windows Security account names containing separators, punctuation, and escaped symbols.
What it assumes
Assumes basic regular-expression syntax and PowerShell pipelines while defining word and non-word character classes directly.
What you can do after
Apply non-word character classes in PowerShell Select-String patterns for log searches that include punctuation or separators.
How it connects
Connects non-word characters with regular expressions, word characters, whitespace, punctuation, character classes, and Select-String.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn PowerShell in a Month of Lunches: Fourth Edition, Covers Windows, Linux, and macOS. The section links point to the parts of the book it draws on.