开发者

regexp that selects only the capital letter from another regexp

I have this type of text:

!D este caro
1 C este descgiderea
C1 este alta deschidere
Deschiderea de 1C este cu
2C
2D
3 D
1NT
2D开发者_StackOverflow
123456P

This easy regexp:

/([0-9][CDHS])/g 

selects "1C","2C","2D","2D" (a digit immediately followed by [CDHS], anywhere in the text) .

What I want is to select only the letter from the sequences above (from "1C" -> only C, from "2D" only D, and so on...). How do I do that with a regexp?

le : While Bolo's method is indeed working in RegExr , in Jquery it appears it doesn't :(

Here's the code :

$(document).ready(function()
      {
                 var de_inlocuit = [/!C/gi, /!D/gi,/!H/gi,/!S/gi,/(?<=[0-9])[CDHS]/g];
       var replace = ['<img src="/sites/default/files/c.gif"/>', '<img src="/sites/default/files/d.gif"/>','<img src="/sites/default/files/h.gif"/>','<img src="/sites/default/files/s.gif"/>','test' ];
       //<img src="/sites/default/files/c.gif"/>
      var i=0;
      for (i=0; i < de_inlocuit.length; i++)
       {
        $('body table tr td').replaceText( de_inlocuit[i], replace[i] );
       } 

      });

The behavior is normal if I remove /(?<=[0-9])[CDHS]/g , but since it was inserted into the code it doesn't even replace the other (surely) working regexp .


To use capturing groups, like with this regex:

/([0-9])([CDHS])/g

...just insert the appropriately numbered group reference into the replacement string, for example:

"rank=$1, suit=$2"

JavaScript regexes do not support lookbehinds, so that approach won't work. The reason @Bolo's solution works in RegExr is because that's a Flex application. Try it in a JavaScript-powered tester like this one and you'll get more relevant results.

Adobe advertises its ActionScript regexes as being compatible with JavaScript's, with an identical list of supported features, but they're actually much more powerful, being powered by the PCRE library. So take care to use a JavaScript tester to test your JS regexes, not a Flex tool like RegExr or RyanSwanson.com.


Take the digit off the capture group:

/[0-9]([CDHS])/g

By the way the original pattern doesn't match strings that have a space in between the letter and the digit. You can allow an optional space with:

/[0-9]\s*([CDHS])/g


First option: use a positive lookbehind:

/(?<=[0-9])[CDHS]/g

Second option: use a capturing group (as mentioned in Aillyn's answer):

/[0-9]([CDHS])/g

In the second case, however, you have to take the contents of the 1st capturing group, instead of the whole match (i.e., group #1 instead of group #0). How to do it depends on the programming language that you're using.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜