Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace character with character itself and hyphen

Tags:

string

regex

php

I need to replace some camelCase characters with the camel Case character and a -.

What I have got is a string like those:

Albert-Weisgerber-Allee 35
Bruninieku iela 50-10

Those strings are going through this regex to seperate 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.

  1. I'm very bad at regex.

  2. Above regex also cuts every - from the streets name, and there are a lot of those names in germany and europe.

Actually it would be quite easy to just adjust the regex to not cut any hyphens, but I want to learn how regex works and so I decided to try to find a regex that just replaces every camel case letter in the string with

- & matched Camel Case letter

except for the first uppercase letter appearance.

I've managed to find a regex that shows me the places I need to paste a hyphen like so:

.[A-Z]{1}/ug     

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

But how on earth do I replace this string:

AlbertWeisgerberAllee 

that it becomes

Albert-Weisgerber-Allee
like image 660
baao Avatar asked Jun 13 '15 20:06

baao


People also ask

How do you include a hyphen in regex?

In regular expressions, the hyphen ("-") notation has special meaning; it indicates a range that would match any number from 0 to 9. As a result, you must escape the "-" character with a forward slash ("\") when matching the literal hyphens in a social security number.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

Can I use regex in replace?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true: If the replacement string cannot readily be specified by a regular expression replacement pattern.


1 Answers

To insert dashes before caps use this regex:

$string="AlbertWeisgerberAllee";
$string=preg_replace("/([a-z])([A-Z])/", "\\1-\\2", $string);
like image 158
umka Avatar answered Sep 28 '22 06:09

umka