regex - positive look ahead and replace -
recently i'm writing/testing regexps on https://regex101.com/.
my question is: possible positive look-ahead , replacement in same "replacement"? or limited kind of replacement possible.
input several lines phone numbers. let's correct phone number number of "numbers" 11. no matter how numbers divided/group - / characters, no matter if starts + 00 or omitted. example lines:
+48301234567 +48/30/1234567 +48-30-12-345-67 +483011223344556677 0048301234567 +(48)30/1234567
positive look-ahead able check if beginning until end of line there 11 digits, regardless how many other, above specified character separating them. works perfectly.
where positive look-ahead check fine, delete every character numbers. replacement works fine until i'm not involving look-ahead.
checking regexp working ("gm" modes):
^(?:\+|00)?(?:[\-\/\(\)]?\d){11}$
checking replace part works (replace nothing):
[^\d\n]
put look-ahead, after deletion of non new-line , non-digit characters matching lines:
(?=^(?:\+|00)?(?:[\-\/\(\)]?\d){11}$)[^\d\n]
even put ^ $ look-ahead, seems replacement working beginning of lines until first digit.
i know in real life replacement , check should/would go separate ways, i'm curious if mix look-ahead/look-behind string operations replace, delete, take string apart , put like.
update: trick, feel 1 "ugly" bit. there prettier solution? https://regex101.com/r/yt5da4/2
or version asked originally, digits remains: regex101.com/r/yt5da4/3
you cannot replace/delete text regex. regex tool matching strings , taking action depending on matching text, eg. perform substitution, retrieve second capture group.
however possible perform decisions within regex engine, using conditionals. common syntax this, lookahead assertion, (?(?=regex)then|else)
.
with conditionals can change behaviour depending on how text matches regex. example like:
^(\+)?(?(1)\(|\d)
if phone number starts plus must followed bracket, else should start digit. although in situation, not useful.
if want read more on conditionals in regex can here.
Comments
Post a Comment