私はこのような文字列を持っています:「プログラミングは私の情熱です、私はプログラムが大好きです」
次に、RegexReplaceを使用してこれを変更する必要があります。「プログラム」という表現を含む各単語は、次のように切り替える必要があります。
<a href="http://codeguru.pl" title="programming">programming</a>
どんな助けでもありがたいです。
String.Replaceはここでより良い賭けです。
var input = "programming is my passion, I love programs";
var replacefrom = "program";
var tobereplaced =@"<a href=""http://codeguru.pl"" title=""programming"">programming</a> is my passion";
var output = input.Replace(replacefrom, tobereplaced)
Regex regex = new Regex("program");
var outputRegex = regex.Replace(input, tobereplaced); // input, tobereplaced from above snipped
出力
<a href="http://codeguru.pl" title="programming">programming</a> is my passionming is my passion, I love <a href="http://codeguru.pl" title="programming">programming</a> is my passions
ワンライナーで十分です:
new Regex(@"\b\w*program\w*\b").Replace("programming is my passion, I love programs", @"<a href=""http://codeguru.pl"" title=""programming"">programming</a>");
ここで\b\w*program\w*\b
、を含むすべての単語に一致しますprogram
。
一致した単語に従ってリンクのテキストを変更する場合は、後方参照を使用します。
new Regex(@"(\b\w*program\w*\b)").Replace("programming is my passion, I love programs", @"<a href=""http://codeguru.pl"" title=""programming"">$1</a>");
このバージョンでは、パターンの前後に角かっこが追加され、$1
(ハードコードされた文字列 " programming
"の代わりに)一致した単語を参照するために使用されます。これで、出力は次のようになります。
<a href="http://codeguru.pl" title="programming">programming</a> is my passion, I love <a href="http://codeguru.pl" title="programming">programs</a>
ソリューション..
Pattern pattern = Pattern.compile("(\\w+|\\W)");
Matcher m = pattern.matcher("programming is my passion, I love programs");
while (m.find())
{
Pattern pattern1 = Pattern.compile("(program)");
Matcher m1 = pattern1.matcher(m.group());
if(m1.find())
System.out.print(m.group().replace(m.group(), "<a href="+"http://codeguru.pl"+" title="+"programming"+">programming</a>"));
else
System.out.print(m.group());
}
出力:
<a href=http://codeguru.pl title=programming>programming</a> is my passion, I love <a href=http://codeguru.pl title=programming>programming</a>