Difference between revisions of "Programming:Regular Expressions"

From WhyAskWhy.org Wiki
Jump to: navigation, search
m (Saving progress)
m (Added recipe for cleaning up copied/pasted directives from nginx wiki/documentation pages.)
Line 22: Line 22:
 
|-
 
|-
 
|<code>.*(scgi.*)".*</code>
 
|<code>.*(scgi.*)".*</code>
|\1
+
|<code>\1</code>
 
|}
 
|}
 +
 +
 +
=== Indent each line 12 spaces, enclose in single quotes and add trailing comma ===
 +
 +
This snippet can be used to apply appropriate spacing and quoting to lines of text that will be used in a PHP array; specifically directives in a GeSHi language file.
 +
 +
{| class="wikitable"
 +
|-
 +
!Find what:
 +
!Replace with:
 +
|-
 +
|<code>^(.*)</code>
 +
|<syntaxhighlight lang="text" enclose="none">            '\1',</syntaxhighlight>
 +
|}
 +
  
 
=== Other ===
 
=== Other ===

Revision as of 23:27, 25 August 2012


Historically, I've avoided Regular Expressions as I've found them cryptic and very difficult to work with. Over the past few years I've had more need for them and have been using them often enough that I'm getting used to the idea of using them.

Lots of power, but still just as cryptic as ever. This page will list various tips/tricks/recipes that I've found useful.


Notepad++

I'm thinking of breaking the entries from the main table into separate sections to emphasize certain points.

Match scgi directives in nginx source code

This snippet can be used to match scgi directives in nginx source code in order to get a listing of valid directives for the scgi module.

Find what: Replace with:
.*(scgi.*)".* \1


Indent each line 12 spaces, enclose in single quotes and add trailing comma

This snippet can be used to apply appropriate spacing and quoting to lines of text that will be used in a PHP array; specifically directives in a GeSHi language file.

Find what: Replace with:
^(.*) '\1',


Other

I've listed these for my use with Notepad++, but some may work well for other purposes also.

Notepad++ Regular Expressions
Regular Expression Purpose Useful for
//\s*.*$ Match on C++ (or C99+) comments and all text after Selecting comments for removal
^(\w) Match the first word character Notepad++ Search box
|\1 Append a "pipe" in front of the first match found in an earlier search Notepad++ Replace box
^\s+$ Match lines that start with whitespace and end with whitespace Notepad++ Search box; search & replace for code cleanup.
\s+$ Match trailing whitespace Notepad++ Search box; search & replace for code cleanup.
^\s+ Match leading whitespace Notepad++ Search box; forced text alignment
[^a-zA-Z_-] Match text prior to nginx directives (ex: 2.21 keepalive_disable) Notepad++ Search box; search & replace for code cleanup.