2009-05-22 15 views
0

私は以下のような文字列を持っています。複数の同一の文字を文字列の1つに置き換えます。

dim str as string = "this  is a string  . " 

複数のスペース文字を識別し、1つのスペース文字で置き換えたいとします。 replace関数を使用するとそのすべてが置き換えられるので、そのようなタスクを実行する正しい方法は何ですか?

+0

を読みやすい\ S +修飾子を、使用したいですDupe。次の記事をチェックしてください:http://stackoverflow.com/questions/206717/how-do-i-place-multiple-spaces-with-a-single-space-in-c –

+0

@chris、 ) –

答えて

0

正規表現を使用してください。この他のSOユーザーによって提案されたようhere

2
import System.Text.RegularExpressions    

dim str as string = "This is a  test ." 
dim r as RegEx = new Regex("[ ]+") 
str = r.Replace(str, " ") 
2

は、「1つ以上のスペース」のパターンに一致する正規表現クラスを使用して、単一のスペースでそれらのインスタンスのすべてを置き換えます。ここで

はそれを行うためのC#コードです:

Regex regex = new Regex(" +"); 
string oldString = "this  is a string  . "; 
string newString = regex.Replace(oldString, " "); 
1

私は

public Regex MyRegex = new Regex(
     "\\s+", 
    RegexOptions.Multiline 
    | RegexOptions.CultureInvariant 
    | RegexOptions.Compiled 
    ); 


// This is the replacement string 
public string MyRegexReplace = " "; 

string result = MyRegex.Replace(InputText,MyRegexReplace); 

またはVB

Public Dim MyRegex As Regex = New Regex(_ 
     "\s+", _ 
    RegexOptions.Multiline _ 
    Or RegexOptions.CultureInvariant _ 
    Or RegexOptions.Compiled _ 
    ) 


Public Dim MyRegexReplace As String = " " 


Dim result As String = MyRegex.Replace(InputText,MyRegexReplace) 
関連する問題