Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an answer to another question I asked that doesn't work with Java because it doesn't support the conditional reference feature.

Since there is an answer that is correct in the general sense of regular expressions I want to get a more specific question on how to do the same thing without the conditional reference feature.

My requirement is to ensure that the pattern in the second matching group is the same pattern in the first matching group. But the the conditional reference in this isn't supported in the Java implementation.

(?i)^(?:([a-z]+)|d+)-(?(1)[a-z]+|d+)$

I have done extensive searching and attempts to modify this to work the same way in Java with no success.

How do I convert this to something that will give the same output but with the restrictions that the Java regular expressions have?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
143 views
Welcome To Ask or Share your Answers For Others

1 Answer

If I understand you correctly you want to make sure that both xx-yy belong to same category (alphabetic, numeric). In case they are place xx in group 1 and yy in group 2.

If that is true then you can use look-ahead to test if string is in form you want to accept, and then place each part in separate groups.

This should do what you want:

(?i)^(?=[a-z]+-[a-z]+$|d+-d+$)([a-zd]+)-([a-zd]+)$

DEMO

Short explanation

  • ^(?=[a-z]+-[a-z]+$|d+-d+$) this look-ahead tests if entire string is in form
    • alpha-alpha
    • OR numeric-numeric
  • ([a-zd]+)-([a-zd]+)$ if lest previously performed by look-ahead was positive we can place matched characters (regardless if they are a-z or d - this was tested previously) to group 1 and group 2.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...