简体   繁体   English

Java正则表达式的前一个字符

[英]Java regex for preceding character

I am trying to construct a regex to check if a letter occurs in a string, it should be precede only one of 2 other characters. 我正在尝试构造一个正则表达式来检查字母是否出现在字符串中,它应仅位于其他2个字符之一之前 I can do this for one set of chars, but how do I do it for multiple sets in a string? 我可以对一组字符执行此操作,但是如何对字符串中的多组字符执行此操作?

For example: C can only precede A or B, ie if C is found the next char can only be A or B. F can only precede D or E (F cannot precede A or B) 例如:C只能在A或B之前,即,如果找到C,则下一个字符只能是A或B。F只能在D或E之前(F不能在A或B之前)

A or B, then C can occur D or E, then F can occur A或B,则C可以发生D或E,然后F可以发生

How do I do this? 我该怎么做呢?

The following gives me an error: 以下给我一个错误:

String pattern = "([F][D|E])|([A][B|C])";
String test = "FEAC";
System.out.println(test.matches(pattern));

Assuming the only allowable letters are A to F, you can use this: 假设唯一允许的字母是A到F,则可以使用以下命令:

^(?:C[AB]|F[DE]|[ABDEG-Z])+$

See the matches in the demo 演示中查看比赛

Explanation 说明

  • The anchors won't be necessary with the matches method, but explaining them for the raw version: 无需使用matches方法的锚,但可以对原始版本进行解释:
  • The ^ anchor asserts that we are at the beginning of the string ^锚断言我们在字符串的开头
  • The $ anchor asserts that we are at the end of the string $锚断言我们在字符串的末尾
  • Match C[AB] a C then an A or B, OR | 匹配C[AB] ,C,然后匹配A或B,或者|
  • F[DE] an F then a D or E, OR | F[DE] a F然后是D或E,或者|
  • [ABDEG-Z] one of these letters [ABDEG-Z]这些字母之一
  • + one or more times +一次或多次

Option: Allowing C and F at the end of the string 选项:在字符串末尾允许C和F

If you want to allow C or F at the end of the string, add this: |[CF]$ (one of several ways to do it) 如果要在字符串的末尾允许C或F,请添加以下内容: |[CF]$ (执行此操作的几种方法之一)

The regex becomes: 正则表达式变为:

^(?:C[AB]|F[DE]|[ABDEG-Z]|[CF]$)+$

In Java: 在Java中:

if (subjectString.matches("(?:C[AB]|F[DE]|[ABDEG-Z])+")) {
    // It matched!
  } 
else {  // nah, it didn't match...  
     } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM