[英]RegEx to replace the first and last character of string for a particular match
Something like this. 这样的事情。
The sentence is 这句话是
string ttt = "This is ?chef? and ?teacher? time";
This sentence should change to 这句话应改为
ttt = "This is 'chef' and 'teacher' time";
I was looking at some online samples Regex.Replace(ttt, @"\\?([^\\$]*)\\?", "REPLACE");
我在看一些在线示例Regex.Replace(ttt, @"\\?([^\\$]*)\\?", "REPLACE");
but I am not able to figure out what should I write in place of REPLACE . 但是我不知道该怎么写代替REPLACE 。 It should be per word basis. 它应该基于每个单词。
Kindly help me with this. 请帮助我。
You would reference the capture group inside the replacement call. 您将在替换调用中引用捕获组。 It's called a back-reference. 这称为反向引用。
String ttt = "This is ?chef? and ?teacher? time";
String result = Regex.Replace(ttt, @"\?([^?]*)\?", "'$1'");
Console.WriteLine(result); //=> "This is 'chef' and 'teacher' time"
Back-references recall what was matched by a capture group ( ... )
. 反向引用回想一下捕获组 ( ... )
所匹配的内容。 A backreference is specified as ( $
); 反向引用指定为( $
); followed by a digit indicating the number of the group to be recalled. 后跟一个数字, 指示要调出的组的号码 。
Note: I used [^?]
for the negation instead of matching everything except a literal $
here. 注意:我使用[^?]
进行取反,而不是匹配此处的文字$
以外的所有内容。
But if you're just wanting to replace ?
但是,如果您只是想更换?
, a simple replacement would suffice: ,一个简单的替换就足够了:
String result = ttt.Replace("?", "'");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.