7

Example strings:

This is "a"  test        
This & test         
This test string-has more words     

In each of the above examples I have strings of words of varying lengths. Each of these strings is followed by a series of spaces and nothing after that.

My application uses () around sections of the regex to return only that portion of the matched pattern if necessary.

I need a regex that will return the full string regardless of length, minus the spaces on the end.

My current is (.*)\s{1,}$|(.*\S)$ This works if there are 0 spaces at the end of the string or 1 space at the end of the string, but 2 spaces or more, and the spaces are included in the output.

Scott Weldon
  • 9,673
  • 6
  • 48
  • 67
Bryan Gauthier
  • 101
  • 1
  • 1
  • 5
  • Welcome to Stack Overflow! Please show us [what you have tried](//whathaveyoutried.com), as well as the specific problem or error that you are encountering. Be sure to include a [Minimal, Complete, Verifiable Example](//stackoverflow.com/help/mcve). – Scott Weldon Jun 27 '16 at 23:32
  • I'm not sure why I'm getting downvoted...I didn't provide my code at first because I posted from my cellphone, but I've added my current regex and I'm still getting downvoted. – Bryan Gauthier Jun 28 '16 at 00:01
  • 1
    You can try: `/.*(?= |$)/`. Also, what language/tool are you using? – Washington Guedes Jun 28 '16 at 00:08
  • It isn't part of any language / code, it is a function of this application we use, and in the app you can write regex. Your provided solution did not remove the trailing spaces. Thank you very much for your attempt. – Bryan Gauthier Jun 28 '16 at 00:14
  • The application has a name? Or at least was it written in any language/tool? Do you want to match from start till the last non-space or to replace the ending spaces? – Washington Guedes Jun 28 '16 at 00:19
  • Well, my last try then: `/\S.*\S/` – Washington Guedes Jun 28 '16 at 00:21

6 Answers6

9

The following regex would trim spaces only from the end of the string:

\s+$/g

Explanation:

  • \s+$ := check the end of the string for any number of white space characters in a row
  • g := search for multiple matches

Similarly, the following regex would also trim spaces from the beginning in addition to the end of the string:

/^\s+|\s+$/g

Explanation:

  • ^\s+ := check beginning of the string for any number of white space characters in a row
  • \s+$ := check the end of the string for any number of white space characters in a row
  • | := "OR", check if either of the patterns,^\s+ or \s+$are present
  • g := search for multiple matches
Kmeixner
  • 1,664
  • 4
  • 22
  • 32
4

your explanation is too small. I don`t know which language you wanna use but I recommend you to use trim function to remove any spaces from beginning and end of a string. but if you insist on use regex, here is a regular expression for your intend:

/^[^ ][\w\W ]*[^ ]/

it removes one or more spaces from beginning and end of your string.
it supports ANY normal character except space. If you need more limitation you may manipulate \w\W statement. If there are bugs in the above expression just tell me.

HosSeinM
  • 301
  • 1
  • 6
  • 14
  • I change a tiny thing please recopy the expression to have best performance. – HosSeinM Jun 28 '16 at 00:08
  • It isn't part of any language / code, it is a function of this application we use, and in the app you can write regex, so I can't use the trim function. Regardless, your regex provided above works flawlessly to remove the trailing spaces, but not spaces at the beginning, but since that wasn't a requirement, I'll award you the answer. Thank you so much. – Bryan Gauthier Jun 28 '16 at 00:10
  • Thank you Bryan. if you don`t want to remove spaces from beginning just remove [^ ] from beginning of the expression. I mean: **/^[\w\W ]*[^ ]/** – HosSeinM Jun 28 '16 at 00:47
4

If you need a regex to do this: ^\s*(\S(.*\S)?)\s*$

Strips any amount of space until a non-whitespace character, then eats any amount of characters until the last non-whitespace, before cutting off all trailing whitespace. Also handles a single character string. Will not match an empty string.

TemporalWolf
  • 7,727
  • 1
  • 30
  • 50
4

This code seems to work: .*\S

And this removes both leading and trailing spaces: \S.*\S

mech
  • 2,775
  • 5
  • 30
  • 38
Chris L
  • 41
  • 1
3

Here's one that actually works. (Tested in javascript)

/^[\s\S]*?(?= *$)/

Special cases that break other answers:

  • Strings containing only spaces
  • Empty strings
  • Strings containing newlines

Explanation:

^ - start of string
[\s\S]*? - match 0 or more (but as few as possible) of any character
(?= - after the match, the string must contain:
 * - 0 or more spaces
$ - and the end of the string
)
Community
  • 1
  • 1
12Me21
  • 992
  • 10
  • 22
3

I tried the several solutions mentioned above and could not find one that would work for any strings, including strings containing new lines in quotes. Even the solution from 12Me12 did not work unfortunately. I use Swift 5.2 and NSRegularExpression.

I found a new solution and it seems to work fine for both strings on a single line and multilines string - even including new lines inside quotes, which will be ignored.

The regular expression I use is "\S[\s\S]*\S"

For example, it will correctly trim the the following string (note the extra space at the beginning):

  {
  "age" : 68,
  "hobbies" : [
    "cooking",
    "guitar"
  ],
  "height" : 175
}

Single lines will be correctly trimmed as well. In the following string:

Trim le please!

the regular expression will match:

Trim le please!

Explanation

So we want to match a first character which is not an empty space: \S, when we can match any whitespace or non-whitespace character. It seems that the dot . does not match whitespaces though, so we have to specify [\s\S]* to match whitespaces and non-whitespaces. Finally we enforce the final character to be a non-whitespace character with \S again.

Hoping this could be useful for future readers of this thread.

Woody
  • 151
  • 1
  • 6