[英]Replace Certain character with regex android
我試圖用正則表達式替換例如: Jack's House
到一個隨機字符串:{“傑森”,“克里斯”,....} Jason's House
使用正則表達式,我只想將“傑克”替換為一個隨機字符串來自 List pLines
,所以這就是我對正則表達式的想法,[A-Za-z] 假設允許隨機字符,\n|' 是允許空格或特殊字符“'”,[S|s] 是允許 s 或大寫 s,“House|house”是允許 House 或 house,最后“^ $”是 startline 和 endline 實現:
public String generateRandomPlaces(String PlaceName){
String HouseRegex = "(^[A-Za-z]+\n|\n|'+[Ss]+House|house$)";
Pattern NameRegex = Pattern.compile(HouseRegex);
Matcher matcher = NameRegex.matcher(PlaceName);
Pname pname = new Pname(this);
pLines = pname.readStr(aPath);
Random rand = new Random();
for(String s : pLines)
if(PlaceName.matches(HouseRegex)){
return PlaceName.replaceAll(s , pLines.get(rand.nextInt(pLines.size())));
}
return PlaceName.replace("([A-Za-z])" , pLines.get(rand.nextInt(pLines.size())));
}
我是用正則表達式做錯了還是需要添加一些東西
您的正則表達式有一些小錯誤,將其更改為:
String HouseRegex = "(^[A-Za-z]+\n|\n|'+[Ss]+House|House$)";
房子->房子
你可以在這里檢查和測試你的正則表達式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.