当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - how to remove double characters and spaces from string

问题描述:

Please let me how to remove double spaces and characters from below string.

String = Test----$$$$19****[email protected]@@@ Nothing

Clean String = Test-$19*[email protected] Nothing

I have used regex "\s+" but it just removing the double spaces and I have tried other patterns of regex but it is too complex... please help me.

I am using vb.net

网友答案:

For a faster alternative try:

        Dim text As String = "[email protected]@@_&aa&&&"

        Dim sb As New StringBuilder(text.Length)
        Dim lastChar As Char
        For Each c As Char In text
            If c <> lastChar Then
                sb.Append(c)
                lastChar = c
            End If
        Next

        Console.WriteLine(sb.ToString())
网友答案:

What you'll want to do is create a backreference to any character, and then remove the following characters that match that backreference. It's usually possible using the pattern (.)\1+, which should be replaced with just that backreference (once). It depends on the programming language how it's exactly done.

Dim text As String = "[email protected]@@_&aa&&&"
Dim result As String = New Regex("(.)\1+").Replace(text, "$1")

result will now contain [email protected]_&a&. Alternatively, you can use a lookaround to not remove that backreference in the first place:

Dim text As String = "[email protected]@@_&aa&&&"
Dim result As String = New Regex("(?<=(.))\1+").Replace(text, "")

Edit: included examples

网友答案:

Here is a perl way to substitute all multiple non word chars by only one:

my $String = 'Test----$$$$19****[email protected]@@@ Nothing';
$String =~ s/(\W)\1+/$1/g;
print $String;

output:

Test-$19*[email protected] Nothing
网友答案:

Here's how it would look in Java...

String raw = "Test----$$$$19****[email protected]@@@ Nothing";
String cleaned = raw.replaceAll("(.)\\1+", "$1");
System.out.println(raw);
System.out.println(cleaned);

prints

Test----$$$$19****[email protected]@@@ Nothing
Test-$19*[email protected] Nothing
分享给朋友:
您可能感兴趣的文章:
随机阅读: