我有一些带有模式的字符串:
15764_Coordinator/Principal Investigator, Curator;44504_Database Manager, Architect;43401_Scientific Expert;43701_Scientific Expert;
此模式中的分隔符是分号;
。假设我有任何起始数字,例如 44504
,我想删除从此数字开始直到分号 ;
的字符串部分。删除后的字符串将是:
15764_Coordinator/Principal Investigator, Curator;43401_Scientific Expert;43701_Scientific Expert;
我怎样才能实现这个目标?
最佳答案
您需要使用string.replaceAll
功能。
string.replaceAll("(?m)(?<=^|;)44504[^;]*;", "")
(?m)
多行修饰符。当您处理正则表达式包含 anchor 的多行输入时,这是必要的(^
、$
)(?<=^|;)
正向lookbehind断言匹配前面必须有分号或行首。[^;]*
否定字符类,匹配任何字符但不匹配;
,零次或多次。
示例:
String s = "15764_Coordinator/Principal Investigator, Curator;44504_Database Manager, Architect;43401_Scientific Expert;43701_Scientific Expert;";
System.out.println(s.replaceAll("(?<=^|;)44504[^;]*;", ""));
输出:
15764_Coordinator/Principal Investigator, Curator;43401_Scientific Expert;43701_Scientific Expert;
关于java - 正则表达式匹配以特定数字开头并以分号结尾的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28810262/