문제

What regex could do the following?

  1. Remove all whitespace except when not between two alphanumeric characters
  2. When between two alphanumeric characters, replace by a single space
도움이 되었습니까?

해결책

A simple solution would be replacing

(\w )\s*(\w)|\s+

With \1\2.

This would replace the possible multiple whitespaces between two alphnum by a single one, and erase all the others. As it is it (obviously) doesn't account for spaces inside quotes and all "special cases" though.

See demo here.

다른 팁

To remove the spaces except when surrounded by alpha-numerics:

'/(?<![a-zA-z0-9 ]) +| +(?! *[a-zA-z0-9])/'

Online Demo 1

And to replace spaces by single space use this regex:

'/(?<=[a-zA-z0-9]) +(?=[a-zA-z0-9])/'

Online Demo 2

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top