开发者

Replace matched characters from regex in a string

I'm trying to figure out how to replace some text in this string:

'some text blah blah XII'

I need to replace the Roman Numerals with an empty string, resulting in:

'some text blah blah'

I have the following regex w开发者_运维百科hich correctly matches a Roman Numeral.

string p1 = "^m*(d?c{0,3}|c[dm])"+ "(l?x{0,3}|x[lc])(v?i{0,3}|i[vx])$";

How do I replace the matches with an empty string?

UPDATE

i tried like this and it doesn't work

string algo = Regex.Replace("some text blah blah XII", "\bm*(d?c{0,3}|c[dm])(l?x{0,3}|x[lc])(v?i{0,3}|i[vx])\b"," ");


The point is that your regular expression matches the whole string, because the regular expression starts with ^ (= beginning of the line/string) and ends with $ (= end of the line/string). To match a single word instead, replace the boundaries ^ and $ by word boundaries, \b.

string p1 = "\bm*(d?c{0,3}|c[dm])(l?x{0,3}|x[lc])(v?i{0,3}|i[vx])\b";

Now the expression matches any isolated word that looks like a roman numeral, and this can be used to replace it.


What about Regex.Replace? Note that you need to remove the anchors from your RE for that to work.


Try Use: Regex.Replace("some text blah blah XII", p1, "");

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜