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?
精彩评论