Jump to content

Deleting whitespace at start of string but not at end

2 replies to this topic

#1 Dave-ee Jones

  • Members
  • 445 posts
  • LocationVan Diemen's Land

Posted 13 October 2017 - 05:21 AM


So, I've got my programming language parser working pretty mint but then realised that it's removing the whitespace on the end of a line. So if I've got a snippet that looks like this:
  what's up?

And I have a space write after 'hey!' on the same line (e.g. 'hey! ') then it will remove the space after 'hey!', which is what I don't want because I want 'what's up?' to appear a space after 'hey!', if you catch my drift.

Here's my current whitespace-removing-technique:

It removes the whitespace line-by-line.

Any help is appreciated. I'm assuming it's just an alteration to the current 'string:match(..)' I have, but since I'm not familiar with the character codes I cannot figure it out myself (maybe remove '(.-)%s*$' at the end?).

Edited by Dave-ee Jones, 13 October 2017 - 05:25 AM.

#2 Kepler

  • Members
  • 39 posts

Posted 13 October 2017 - 05:50 AM

Here's what I use:

-- http://snippets.luac..._from_string_76
function trim(s)
  return s:find'^%s*$' and '' or s:match'^%s*(.*%S)'

-- trim whitespace from left end of string
function triml(s)
  return s:match'^%s*(.*)'

-- trim whitespace from right end of string
function trimr(s)
  return s:find'^%s*$' and '' or s:match'^(.*%S)'

Edited by Kepler, 13 October 2017 - 05:53 AM.

#3 Grim Reaper

  • Members
  • 502 posts
  • LocationSeattle, WA

Posted 15 October 2017 - 05:33 AM

If I understand what you're asking, here's a quick solution I thought up. My Lua skills are rusty, but the test scenario you described checks out.

local codeSnippet =
what's up?

local function parseLineTrimWhiteSpaceAtBackKeepAtFront(line)
   return line:match("[%s]*([^%s]*%s*)")

local function parseSnippetIntoSingleLine(codeSnippet)
   local parsedLines = {}
   local lineNumber = 1
   for line in codeSnippet:gmatch("[^\n+]+") do
	  parsedLines[lineNumber] = line
	  lineNumber = lineNumber + 1
   return parsedLines

local function combineParsedLinesIntoSingleLine(parsedLines)
   local combinedLine = ""
   for _, line in ipairs(parsedLines) do
	   combinedLine = combinedLine .. line
   return combinedLine

local function getContentLineFromCodeSnippet(codeSnippet)
   local parsedLines = parseSnippetIntoSingleLine(codeSnippet)
   return combineParsedLinesIntoSingleLine(parsedLines)

-- Output (quotes to define string start/stop): "hey! what's up?"

Edited by Grim Reaper, 15 October 2017 - 05:33 AM.

1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users