Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to trim spaces from the end of unknown length strings of words

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.

like image 277
Bryan Gauthier Avatar asked Jun 27 '16 23:06

Bryan Gauthier


Video Answer


4 Answers

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
like image 70
Kmeixner Avatar answered Nov 17 '22 00:11

Kmeixner


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.

like image 34
HosSeinM Avatar answered Nov 17 '22 00:11

HosSeinM


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.

like image 23
TemporalWolf Avatar answered Nov 17 '22 00:11

TemporalWolf


This code seems to work: .*\S

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

like image 35
Chris L Avatar answered Nov 16 '22 22:11

Chris L