开发者

Regular Expression Question regarding search&replace

开发者 https://www.devze.com 2023-01-31 22:34 出处:网络
I\'m trying to match cases with regular expression to search and replace some text of given pattern. I can match t开发者_如何学JAVAhe pattern, but I\'d like to keep some of the literals when replacing

I'm trying to match cases with regular expression to search and replace some text of given pattern. I can match t开发者_如何学JAVAhe pattern, but I'd like to keep some of the literals when replacing.

For example, from the string "abcd123," I'd like to keep abcd but remove 123. I can match the pattern using a simple regular expression like [a-zA-Z0-9]+, but when I want to replace it, I don't know what to use for the replacement. Is this even possible with just regular expressions?

Thanks a lot.


The answer depends on what language/regex engine you are using. You typically use parentheses to save sections matched and either $1, $2, ... or \1, \2, ... in the replacement string to refer to those sections.

For example, from JavaScript:

var x = "Hello World";
x.replace( /([A-Z])\w+/g, '$1xx' );
// "Hxx Wxx"

What language or text editor are you using?

0

精彩评论

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