Removing space from string with regex

I can find spaces in the following line:

"____ Input from ABC" <note that there are 4 spaces at the beginning of this line.

with this regex:

[a-z] [a-z]

      

How to replace "t f" with "tf" and "m A" with "mA"? I guess I need to use groups, but I don't remember how. Any advice will be taken into account.

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

+3


source to share


6 answers


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

You need to use a capture group like:

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

      

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



and then use a function to revert them to your desired template:

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

      

\ X refers to the X-th parenthesis group

+1


source


Just use \s

and replace with empty string ""

. You can also use literal space, which will work great too. Remember to use the global flag.

That is, use /\s/g

or / /g

and replace with""




As far as your update goes, you can still use the above regex and then just add four lines to the string, which is pretty efficient. If you still want regex you can use

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

      

and replace with ""

(empty string)

+3


source


use regex: s / \ s // g this should work with perl.

echo "Input from ABC"|perl -pe 's/\s//g'
>InputfromABC

      

+1


source


You can use (*SKIP)(*F)

as shown below,

^\s+(*SKIP)(*F)|\s

      

Then replace the matched spaces with an empty string.

+1


source


in a regex you cannot replace a value with another, you can detect a specific character or whatever you put in your expression, after which you must replace if that character is found.

 [a-z]+\\s

      

the above expression will detect white spaces, after which you can replace the string

+1


source


Your best bet is to look for this:

(^\s+)|\s+

      

and replace with $1

to leave spaces at the beginning of the line. Demo here:

https://regex101.com/r/qQ9dL9/1

+1


source







All Articles