简体   繁体   English

Java 正则表达式:多个以“-”开头的分隔符

[英]Java regex: Multiple delimiters preceded by "-"

Remove suffix from network name of hosts at specific delimiters preceded by "-"hyphen, so that if there are other combinations with "-", it should be taken as part of the network name.去除主机网络名称后缀,以“-”连字符开头的特定分隔符,这样如果有其他“-”组合,则应将其作为网络名称的一部分。

Few examples:几个例子:

abcd-new     --> abcd-new   ## Stays same ##
efgh-nic     --> efgh       ## delimiter is '-nic' ##
mnop-ilo-a   --> mnop-ilo   ## delimiter is '-a' ##
xyz-a01      --> xyz-a01   ## Stays same ##
vm-1-ad-nic  --> vm-1-ad    ## delimiter is '-nic' ##
vm-lab-nic1  --> vm-lab-nic1 ## Stays same ##

The delimiting characters are 'nic', 'a' only.分隔字符仅为“nic”、“a”。 Other combinations of "-" & characters should be kept intact. “-”和字符的其他组合应保持不变。

How do I achieve the above using java regex ?如何使用 java regex 实现上述目标?

If possible, please suggest a single liner...如果可能的话,请建议一个单一的班轮...

You can do this with a String#replaceAll method:您可以使用String#replaceAll方法执行此操作:

str = str.replaceAll("-(nic|a)\\b", "");

Regex -(nic|adm) matches a hyphen followed by nic or adm .正则表达式-(nic|adm)匹配连字符后跟nicadm

\\\\b is for word boundary to make sure we don't match unwanted text like abc . \\\\b用于单词边界以确保我们不匹配不需要的文本,例如abc

You can add more suffixes in this group that you want to be removed.您可以在该组中添加更多要删除的后缀。

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

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