Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我的字符串模式是
"hbfj-nbsp-nbsp-wsefj-f-ejsf-sdfh-sjkf-df-sdjfk-sdfhb-jdgh-nbsp-djg-hdr"
我已经尝试过这种模式"(\\w+)-(\\w+)-(\\w+)-(\\w+)",但它给出了完全匹配。要求匹配"hbfj-"此类字符串的 0 到 3 次。
"(\\w+)-(\\w+)-(\\w+)-(\\w+)"
"hbfj-"
尝试使用这个正则表达式:string.matches("^(\\w+(-|$)){0,3}$")
string.matches("^(\\w+(-|$)){0,3}$")
我认为您想提取第一个连字符分隔的单词(最多 4 个):
String words = str.replaceAll("^(\\w+(-\\w){0,3})?.*", "$1");
如果没有找到合适的,这将返回一个空白。