我想将下面的字符串拆分成+,但是我无法成功地获得正确的正则表达式。
String input = "SOP3a'+bEOP3'+SOP3b'+aEOP3'";我想得到这样的结果
[SOP3a'+bEOP3', SOP3b'+aEOP3']在某些情况下,我可能有以下字符串
c+SOP2SOP3a'+bEOP3'+SOP3b'+aEOP3'EOP2应该被分割成
[c, SOP2SOP3a'+bEOP3'+SOP3b'+aEOP3'EOP2] 我试过下面的正则表达式,但它不起作用。
input.split("(SOP[0-9](.*)EOP[0-9])*\\+((SOP)[0-9](.*)(EOP)[0-9])*");如有任何帮助或建议,敬请见谅。
谢谢
发布于 2017-02-24 19:08:34
您可以使用下面的regex来匹配字符串,通过使用捕获的组替换它,您可以得到预期的结果:
(?m)(.*?)\+(SOP.*?$)请参阅演示/解释
以下是Java中适用于您的代码:
public static void main(String[] args) {
String input = "SOP3a'+bEOP3'+SOP3b'+aEOP3'";
String pattern = "(?m)(.*?)\\+(SOP.*?$)";
Pattern regex = Pattern.compile(pattern);
Matcher m = regex.matcher(input);
if (m.find()) {
System.out.println("Found value: " + m.group(0));
System.out.println("Found value: " + m.group(1));
System.out.println("Found value: " + m.group(2));
} else {
System.out.println("NO MATCH");
}
}m.group(1)和m.group(2)是您要寻找的值。
发布于 2017-02-24 18:40:25
你真的需要使用split方法吗?规则是什么?我对他们不太清楚。
无论如何,考虑到您提供的正则表达式,我只删除了一些不必要的组,并且找到了您要寻找的内容,但是,我加入了匹配,因为拆分它会生成一些空元素。
const str = "SOP1a+bEOP1+SOP2SOP3a'+bEOP3'+SOP3b'+aEOP3'EOP2";
const regex = RegExp(/(SOP[0-9].*EOP[0-9])*\+(SOP[0-9].*EOP[0-9])*/)
const matches = str.match(regex);
console.log('Matches ', matches);
console.log([matches[1],matches[2]]);
https://stackoverflow.com/questions/42445754
复制相似问题