More Regex Questions

I doubt I will EVER get my head wrapped around how to craft a proper RegEx statement.

Here is what I need to do

  1. Trim trailing whitespace from WITHIN a block of text…
This is a test          ^
of an example   ^
piece of text   ^

where ^ if EOL
would become

This is a test^
of an example^
piece of text^

and it should also accomodate the text ending in whitespace but no trailing EOL

in Addition I need another RegEx to trim LEADING white space in a similar manner

I tried this
[^ \t\r\n])[ \t]+$"
but worked, but also removed the last non whitespace character

Hi Dave - Try this one to see if this what you are looking for:

(?-U)(?!(\w))\s+(?=\B)

HTH
Mike

It didn’t work

s=s.replacingOccurrences(of: "(?-U)(?!(\\w))\\s+(?=\\B)", with: "", options: .regularExpression)

note : Swift does required the \ be doubled up (escape )

FYI… This works for removing LEADING whitespace

s=s.replacingOccurrences(of: "^\\s+"  , with: "", options: .regularExpression)
s=s.replacingOccurrences(of: "\\n\\s+", with: "\n", options: .regularExpression)
1 Like

How about

s=s.replacingOccurrences(of: "\\s+$"  , with: "", options: .regularExpression)
s=s.replacingOccurrences(of: "\\s+\\n", with: "\n", options: .regularExpression)

Strange… I swear I had tried exactly that earlier… but it did work… thanks