Home > Net >  How to add space after comma if it has letters on each side in a string using RegEx(Java)
How to add space after comma if it has letters on each side in a string using RegEx(Java)

Time:04-19

Example String = "abcd,anhdc,bajb,abchb,njacsn,10,000,nijaxiu"

Result = "abcd, anhdc, bajb, abchb, njacsn, 10,000, nijaxiu"

Space should not be there after 10, as it is Integer

CodePudding user response:

You didn't mention which environment you are attempting to solve this problem in. So the following answer is written with the assumption that you are working with Python.

Example string:

abcd,anhdc,bajb,abc1hb,nj2acsn,10,000,nijaxiu

This code in Python should get the job done:

import re

s  = "abcd,anhdc,bajb,abc1hb,nj2acsn,10,000,nijaxiu"

blocks = re.findall('[a-zA-Z0-9] ', s)
seperated_blocks = ''
seperated_blocks  = blocks[0]   ','

for idx in range(1, len(blocks), 1):
  if re.match('\d ', blocks[idx-1]) and re.match('\d ', blocks[idx]):
    seperated_blocks  = blocks[idx] ','
  else:
    seperated_blocks  = ' '   blocks[idx] ','

seperated_blocks = seperated_blocks[0:-1]

Output:

'abcd, anhdc, bajb, abc1hb, nj2acsn, 10,000, nijaxiu'

CodePudding user response:

Shouldn't your result be

abcd, anhdc, bajb, abchb, njacsn,10,000, nijaxi

If this is the output you require and you don't mind making a new string then you can simply use the following code:

s = "abcd,anhdc,bajb,abchb,njacsn,10,000,nijaxiu"
new_s = ""
for i in range(len(s)-1):
    new_s  = s[i]
    if(s[i] == ',' and s[i 1].isalpha()):
        new_s  = " "
print(new_s)
  • Related