简体   繁体   中英

Regex first character before word

I have the following text:

Aida [09/01/2019 11:24:17]: This is just some of the things I can help you with. Aida [09/01/2019 11:24:18]: You can read more detailed descriptions about the processes on the right hand side. Employee [09/01/2019 11:24:23]: can't log in to bolanAida [09/01/2019 11:24:25]: What is the user ID?Employee [09/01/2019 11:24:28]: x0000yAida [09/01/2019 11:25:21]: Bolån production account x0000y is now enabled. Aida [09/01/2019 11:25:23]: You can read more detailed descriptions about the processes on the right hand side. Aida [09/01/2019 11:44:43]: This conversation has been closed.

There are few occurences where there is a character before a word like Aida or Employee (no space between words)

bolanAida, x0000yAida, ID?Employee

and I would like to add spaces between these words in the whole text.

bolan Aida, x0000y Aida, ID? Employee

Maybe you have any regex ideas on how to accomplish that?

Thanks in advance

This kind of things can be accomplished with a backreference and a capture group. Depending on the language you are using, you have to adjust this ruby example:

> string = 'bolanAida, x0000yAida, ID?Employee Aida'
 => "bolanAida, x0000yAida, ID?Employee Aida" 
> string.gsub( /(\S)Aida/, '\1 Aida')
 => "bolan Aida, x0000y Aida, ID?Employee Aida" 

The capture group is (\\S), selecting any non-space character. This is backreferenced in ruby with \\1, but in other languages this may be $1 or regex-group(1)

import re

str = 'Aida Employee bolanAida, x0000yAida, ID?Employee Aida'
print re.sub(r'(?<=\S)(?=Aida|Employee)', ' ', str)

Output:

Aida Employee bolan Aida, x0000y Aida, ID? Employee Aida

Explanation:

(?<=\S)             # positive lookbehind, make sure we have a non space before
(?=Aida|Employee)   # positive look ahead, make sure we have Aida or Employee after

lookaround

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM