Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple periods in string with just one period

I'm trying to replace any group of two or more periods with just a single period. I suspect the + operator is involved, but I've had nothing but sorrow trying to make the expression using that... So I thought as an experiment I would try to replace just 3 periods with one period. The nonsense below is what I came up with, and of course it doesn't work.

OutNameNoExt:= RegExReplace(OutNameNoExt,"\.\.\." , ".")

Or even better, can I alter this existing expression

OutNameNoExt:= RegExReplace(OutNameNoExt,"[^a-zA-Z0=9_-]" , ".")

so that it never produces more than one period in a row?

Help?

like image 669
dwilbank Avatar asked Feb 20 '23 11:02

dwilbank


2 Answers

OutNameNoExt:= RegExReplace(OutNameNoExt,"\.{2,}" , ".")

Or, if the {n,m} (i.e., at least n, but no more than m times) syntax is not allowed, you can use the following instead:

OutNameNoExt:= RegExReplace(OutNameNoExt,"\.\.+" , ".")

Alternatively, you can also change the existing expression to the following so that it doesn't produce more than one period in a row:

OutNameNoExt:= RegExReplace(OutNameNoExt,"[^a-zA-Z0=9_-]+" , ".")
like image 170
João Silva Avatar answered Mar 04 '23 05:03

João Silva


For Java, the following regex is working to replace multiple dots with single dot:

String str = "-.-..-...-.-.--..-k....k...k..k.k-.-";
str.replaceAll("\\.\\.+", ".")

Output:

-.-.-.-.-.--.-k.k.k.k.k-.-
like image 31
Mahesh Avatar answered Mar 04 '23 04:03

Mahesh