How to compare string and ignore white space and cases?

Exmple Input :

var a = Mark N Lautz
var b = Mark N                                  Lautz

It should return true since the same string the only difference it white spaces. Thanks.

Hi @AhmedKutraphali

if(a.replaceAll(“\s+”,“”).equalsIgnoreCase(b.replaceAll(“\s+”,“”)))

3 Likes

@AhmedKutraphali,

You can use = operator to compare string,

if a = b {
// do your work
}

Hi,

Can you try the following condition?

System.Text.RegularExpressions.Regex.Replace(a,"\s+"," ").ToLower=System.Text.RegularExpressions.Regex.Replace(b,"\s+"," ").ToLower

Regards,

1 Like

str = str.replace(chr(160),“”)

U can use contains operation

b.Contains(a)

1 Like

the output should be true , but the regex gives false @Yoichi

.contains does not ignored the white spaces

Hi,

In my environment, it works. Is there any difference with your input string in the following sample?

Sequence4.xaml (5.5 KB)

Regards,

@Yoichi , here is the sample difference between 2 strings when I log it

image

Hi,

Thank you for sharing. However, i cannot reproduce it’s false using the regex.
Can you share them as a text file?

Regards,

is there a way to remove all the spaces ? so the comparison would be

var a = MarkNLautz
var b = MarkNLautz

Hi

is there a way to remove all the spaces ?

It’ll be the following.

System.Text.RegularExpressions.Regex.Replace(a,"\s+","").ToLower=System.Text.RegularExpressions.Regex.Replace(b,"\s+","").ToLower

If you want to delete all white space, the following will work.

newA = System.Text.RegularExpressions.Regex.Replace(a,"\s+","")

(We can check it using LogMessage and/or MessageBox etc)

Regards,

1 Like

I dont really understand why it returned false

1 Like

based on the screenshot above that is just the 2 strings I am comparing

Hi,

We need exact String to investigate the cause. So can you try to write content of variables to text file as the following and share them?

img20210524-3

Regards,

@Yoichi


Hi,

Can you upload the text files to this topic?

Regards,

Thanks @Yoichi , I was able to fix it now hehe

1 Like

For an alternative VB.NET solution that doesn’t use regex:

If String.Equals(a.Replace(" ", ""), b.Replace(" ", ""), StringComparison.InvariantCultureIgnoreCase) Then
    Console.WriteLine("It's a match")
End If
3 Likes