[英]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.