java - 正则表达式匹配以特定数字开头并以分号结尾的字符串

标签 java regex

我有一些带有模式的字符串:

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/

相关文章:

Java图像比较类-添加偏移量

javascript - 正则表达式星号用法

Javascript正则表达式获取双引号内的内容

java - 解析并删除java正则表达式中的特殊字符

java - Spring 如何适应我的应用程序架构?

java - 我是否正确使用了这个处理程序和执行器(Android)?

java - Android——为一个连接打开多个套接字(输入和输出流)

regex - bash sed/grep 提取两个词之间的文本

c# - 使用正则表达式从字符串中获取数字,但没有得到预期的结果

javascript - 如何在js中使用.match(regEx)仅获取没有分隔符的内部字符串?