Regular expression to replace a character with a hyphen

I need to replace some camelCase characters with a Camel case character and - .

I have a line like:

 Albert-Weisgerber-Allee 35 Bruninieku iela 50-10 

These lines go through this regular expression to separate the number from the street:

 $data = preg_replace("/[^ \w]+/", '', $data); $pcre = '\A\s*(.*?)\s*\x2f?(\pN+\s*[a-zA-Z]?(?:\s*[-\x2f\pP]\s*\pN+\s*[a-zA-Z]?)*)\s*\z/ux'; preg_match($pcre, $data, $h); 

Now I have two problems.

  • I feel really bad at regex.

  • The above regular expression also abbreviates each - from the street name, and in Germany and Europe there are many of them.

Actually, it would be easy to just set up the regular expression so as not to cut hyphens, but I want to find out how the regular expression works, and so I decided to try to find a regular expression that simply replaces every camel line letter in a line with

 - & matched Camel Case letter 

except for the first appearance of the letter in uppercase.

I managed to find a regular expression that shows me the places I need to insert a hyphen like this:

 .[AZ]{1}/ug 

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

But how can I replace this line:

 AlbertWeisgerberAllee 

what is he getting

 Albert-Weisgerber-Allee 
+6
source share
3 answers

To insert a dash in front of caps, use this regex:

 $string="AlbertWeisgerberAllee"; $string=preg_replace("/([az])([AZ])/", "\\1-\\2", $string); 
+5
source

Just use capture groups:

 (.)([AZ]) //removed {1} because [AZ] implicitly matches {1} 

And replace with $1-$2

See https://regex101.com/r/qI2iA9/3

+1
source

You seem to make the expression too complicated. You can use the following to place - before any capital letters except the first:

 (.)(?=[AZ]) 

Just replace it with $1- . Essentially what this regex does:

  • (.) Find any character and put this character in group 1.
  • (?=[AZ]) See if the uppercase character follows.
  • $1- If matched, replace the character found in group 1 and then the hyphen.
+1
source

Source: https://habr.com/ru/post/989071/


All Articles