Simplified question to cut text and rename

Finding the first non-blank line doesn’t require regular expressions.

Although this will fail if there is white-space within a “blank” line that precedes any text.


tell application "TextWrangler"
	tell text of front text window
		set fileNameText to contents of first line whose contents is not ""
	end tell
end tell

Hi Chris,

I didn’t know that ‘.’ (dot or period) meant not white space. I thought that the period meant any character but some end of line or end of file. I’ll have to look at that again.

Edited: I see now. You don’t want the name to start with white space. Need to think about that.

Thanks,
kel

Finding “…*\n” will find a line starting with whitespace or containing only whitespace.

Remember that ‘.’ is any character.

The search-options required for this job are minimal.

The following regex finds the text of the first line that starts with a non-whitespace character.


tell application "TextWrangler"
	tell text of front text window
		set findReco to find "^\\S.*" options {search mode:grep, starting at top:true}
	end tell
	if found of findReco is true then
		set foundText to found text of findReco
	else
		error "Text was not found!"
	end if
	set fileName to replace "\\A\\s*(\\S+.+?)\\s*$" using "\\1" searchingString foundText options {search mode:grep}
end tell

The problem with using the result here is that the text may contain trailing whitespace, so I’d want to massage the text before using it. The last line of the script removes any leading or trailing whitespace (although the find regex prevents any leading whitespace).

Hey kel,

‘.’ indeed finds any character including whitespace but excluding EOL characters unless you use the magic dot modifier (?s).

So “…*\n” will find:

“\n”

or

“Something\n”

Etcetera.

So lets try to make the pattern more specific:

^ == Anchor at beginning of line.
\S == Non-whitespace character.
. == Any character.

  • == Zero or more.

^\S.*

That still leaves us with possible trailing whitespace, but I’ve addressed that in my last script.

It’s handy that TextWrangler allows replacing within a string.

This is a bit easier with the Satimage.osax which is why I use it so much.

Hi Chris,

I was thinking that in the search, there would be something like: “first line that does not start with space, linefeed, or eof”. Then, we can use that as the name. I forgot how to to ‘and’ in the regular expression.

Thanks,
kel

My previous pattern will do that, but you can be more specific:

^[^[:blank:]].+

Beginning of line; any-non-horizontal-whitespace-character; any-character-zero-or-more.