Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing space from string with regex

Tags:

regex

I can find spaces in the following string:

"____Input from ABC" << please note there are 4 spaces at the beginning of this string

using this regex:

[a-z] [a-z]

How can I replace"t f" with "tf" and "m A" with "mA"? I guess I have to use groups but I don't remember how. Any advice would be appreciated.

P.S. Please note that there are 4 spaces at the beginning of the string I don't want to remove them.

like image 210
B Faley Avatar asked Jan 24 '26 04:01

B Faley


2 Answers

Just use \s and replace with empty string "". You could also use literal space which too will work perfectly. Just remember to use global flag.

That is, use /\s/g or / /g and replace with ""


Regarding your update, you could still use the above regex and then just add four spaces to the string, which is quite efficient. If you still want a regex, you could use

(?<=\w)\s(?=\w)

and replace with ""(Empty string)

like image 128
Amit Joki Avatar answered Jan 27 '26 01:01

Amit Joki


Depending on the language you are using, you should have a "replace" function

You have to use capturing group, like so :

([a-z]) ([a-z])

http://www.regular-expressions.info/refcapture.html

and then use the function to get them back in the pattern you want :

newString = oldString.replace("([a-z]) ([a-z])", "\1\2")

\X reference the Xth group of parenthesis

like image 31
BlueMagma Avatar answered Jan 27 '26 00:01

BlueMagma