regex 从列表中搜索一个单词或一个字符

jhkqcmku  于 2023-02-25  发布在  其他
关注(0)|答案(1)|浏览(128)

我在公式化正则表达式字符串以匹配“-“或数组[ _-.]中的任何字符时遇到了麻烦。|[ _-.])
我的Java测试程序:

cutAddressStreet("strassen name 1344"); // "strassen name" ok
cutAddressStreet("strassen name-1344"); // "strassen name" ok
cutAddressStreet("strassen name - 1344"); // "strassen name -"  <- Problem
cutAddressStreet("strassen name,1344"); // ""  ok
public static String cutAddressStreet(String sFull)
{
   String sRet = "";
   String sRegEx = "^(.*)( - |[ _\\-\\.])(\\d{1,5})(.*)$";
   if (sFull.matches(sRegEx))
   { // Yes , this is Street with Number
      String sStreet = sFull.replaceFirst(sRegEx, "$1");
      System.out.println("cut=\"" + sStreet + "\" from " + sFull);
      sRet = sStreet;
   }
   return sRet;
}

https://regex101.com/r/ZUg5Z3/1

vfh0ocws

vfh0ocws1#

如果只替换为捕获组1,则模式中不需要3个捕获组。第一个.*匹配整个字符串,因此其中一个捕获组应该是非贪婪的。
字符类中的-可以放在末尾,这样你就不必转义它,也不必转义字符类中的点.
在代码中,您可以直接使用return sStreet;,而不是先覆盖字符串sRet

public static String cutAddressStreet(String sFull)
{
    String sRet = "";
    String sRegEx = "^(.*?)(?: - |[ _.-])\\d{1,5}$";
    if (sFull.matches(sRegEx))
    {
        String sStreet = sFull.replaceFirst(sRegEx, "$1");
        System.out.println("cut=\"" + sStreet + "\" from " + sFull);
        return sStreet;
    }
    return sRet;
}

代码的输出:

cut="strassen name" from strassen name 1344
cut="strassen name" from strassen name-1344
cut="strassen name" from strassen name - 1344

相关问题