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.
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 rowg
:= search for multiple matchesSimilarly, 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 presentg
:= search for multiple matchesyour 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.
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.
This code seems to work: .*\S
And this removes both leading and trailing spaces: \S.*\S
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With