Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

java - Porting a regular expression to a more restrictive regular expression implementation that does not support conditional references

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

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

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...