[英]split a string without adjacent characters that matched regex in java
我是第一个到这个网站的。 我想在 java 的字符串拆分方法的正则表达式中拆分没有匹配字符的字符串。
用于拆分的字符串是(例如): "conditional&&operator and ampersand&Symbol."
我吐的正则表达式是: "[^\\&]\\&[^\\&]"
我的期望是: [conditional&&operator and ampersand, Symbol]
但是,output 是: [conditional&&operator and *ampersan, ymbol*]
我使用的代码是:
String s = "conditional&&operator and ampersand&Symbol.";
String[] sarr = s.split("[^\\&]\\&[^\\&]");
System.out.println(Arrays.toString(sarr));
所以,请告诉我我应该使用什么正则表达式来获得预期的 output,即没有删除额外的字符。
我想不可能按照你的意愿用正则表达式分割你的字符串。 问题是[^\\&]\\&[^\\&]
匹配 3 个字符 -> d&S
并且它被 3 个字符分割,因此您将它们删除。 您可以使用Pattern
和Matcher
以这种方式拆分字符串:
String s = "conditional&&operator and ampersand&Symbol.";
final Matcher matcher = Pattern.compile("[^&]&[^&]").matcher(s);
if (matcher.find()) {
final int indexOfMatchStart = matcher.start();
final String firstPart = s.substring(0, indexOfMatchStart + 1); // + 1 to include first symbol of RegEx
final String secondPart = s.substring(indexOfMatchStart + 2); // + 2 to skip &
System.out.println(firstPart + secondPart); // will print conditional&&operator and ampersandSymbol.
}
尝试这个,
长代码但基本逻辑。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class B {
public static void main(final String[] args) {
final String x = "conditional&&operator and ampersand&Symbol.";
final String mydata = x;
String delimString = "";
final Pattern pattern = Pattern.compile("[^\\&]\\&[^\\&]");
final Matcher m = pattern.matcher(mydata);
while (m.find()){
delimString = m.group(0);
}
final String[] result = x.split(delimString); // Split using 'd&S'
final String[] conResult = delimString.split("&"); //Split d&S in d and s
System.out.println(result[0]+""+conResult[0]); // append d at the end of string
System.out.println(conResult[1]+""+result[1]); // append s at the start of string
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.