开发者

how to group in regex matching correctly?

开发者 https://www.devze.com 2023-04-02 23:57 出处:网络
consider following scenario input string = \"WIPR.NS\" i have to replace this with \"WIPR2.NS\" i am using following logic.

consider following scenario

input string = "WIPR.NS"

i have to replace this with "WIPR2.NS"

i am using following logic.

match pattern =  "(.*)\.NS$"    \\ any string that ends with .NS

replace pattern = "$12.NS"

In above case, since there is no group with index 12, i get result $12.NS

But what i want is "WIPR2.NS".

If i don't have digit 2 to replace, it works in all other cases but not working for 2.

How to resolve this case?

Thanks in adva开发者_Go百科nce, Alok


Usually depends entirely on your regex engine (I'm not familiar with those that use $1 to represent a capture group, I'm more used to \1 but you'd have the same problem with that).

Some will provide a delimiter that you can use, like:

replace pattern = "${1}2.NS"

which clearly indicates that you want capture group 1 followed by the literal 2.NS.


In fact, by looking at this page, it appears that's exactly the way to do it (assuming .NET):

To replace with the first backreference immediately followed by the digit 9, use ${1}9. If you type $19, and there are less than 19 backreferences, the $19 will be interpreted as literal text, and appear in the result string as such.


Also keep in mind that Jay provides an excellent answer for this specific use case that doesn't require capture groups at all (by just replacing .NS with 2.NS).

You may want to look into that as a possibility - I'll leave this answer here since:

  • it's the accepted answer; and
  • it probably better for the more complex cases, like changing X([A-Z])4([A-Z]) with X${1}5${2}, where you have variable text on either side of the bit you wish to modify.


You don't need to do anything with what precedes the .NS, since only what is being matched is subject to replacement.

match pattern = "\.NS$" (any string that ends with .NS -- don't forget to escape the .)
replace pattern = "2.NS"

You can further refine this with lookaround zero-width assertions, but that depends on your regex engine, and you have not specified the environment/programming language in which you are working.

0

精彩评论

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