2 回答

TA貢獻1848條經驗 獲得超6個贊
如果您所要做的就是根據用戶輸入輸出真或假,您可以將代碼字符串轉換為正則表達式并檢查輸入是否與正則表達式列表匹配。
腳步:
將代碼列表中的每個元素轉換為正則表達式
// 將 "ABC(Q,E,1)EEE" 轉換為 "ABC[QE1]EEE" 以匹配以 ABC 開頭、后跟 [QE1] 之一并以 EEE 結尾的每個字符串
//"R(1,2,3,4,5)RT(U,M,N,B,V,H)(Q,E,R,F,G,H)(R,Z)" 到 " R[12345]RT[UMNBVH][QERFGH][RZ]"
ETC
檢查輸入是否匹配正則表達式之一
例子:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the code you want to check: ");
String input = scan.next();
List<String> codes = new ArrayList<>();
codes.add("ABC(Q,E,1)EEE");
codes.add("ABDCE(E,Z,X)E");
codes.add("B(A,1)AAEEE");
codes.add("R(1,2,3,4,5)RT(U,M,N,B,V,H)(Q,E,R,F,G,H)(R,Z)");
codes.add("B(A,1)AA(E,Z)EE");
//list to store the modified strings
List<String> modifiedCodes = new ArrayList<>();
//for each string in list find if there is a pattern like '('some chars')'
Pattern p = Pattern.compile("\\(.*\\)");
for (Iterator<String> i = codes.iterator(); i.hasNext();) {
String code = i.next();
StringBuffer sb = new StringBuffer ();
Matcher m = p.matcher(code);
while (m.find()) {
String match = m.group();
//if found a match replace '(' and ')' with '[' and ']' and remove commas
m.appendReplacement(sb, match.replace('(', '[').replace(')', ']').replace(",", ""));
}
m.appendTail(sb);
//add modified string to list
modifiedCodes.add(sb.toString());
}
boolean codeIsPresent = false;
for(String code: modifiedCodes){
//check if input matches one of the regex in the list 'modifiedCodes'
if (input.matches(code)) {
codeIsPresent = true;
System.out.println("True: This code is present");
break;
}
}
if(!codeIsPresent){
System.out.println("Code not found");
}
}
編輯
我們如何打印從中獲取輸出的字符串的所有組合的列表?比如說,我只有一個字符串“BA(1,2,3)QW(AZ,0-9)”,我想要它的所有可能組合
您評論中的上述問題與原始帖子略有不同,如果您發(fā)布一個新問題可能會更好。您可以使用某種樹形結構創(chuàng)建自己的算法來解決問題,但它可能非常笨拙和混亂。如果可能的話,我建議使用像generex這樣的第3 方圖書館。你可以從這里的 maven repo下載 jar 。使用generex,您可以擁有所有可能的組合:
public static void main(String args[]){
//change your input to a regular expression
//"BA(1,2,3)QW(A-Z,0-9)" to "BA[1-3]QW[A-Z][0-9]"
Generex generex = new Generex("BA[1-3]QW[A-Z][0-9]");
List<String> matchedStrs = generex.getAllMatchedStrings();
matchedStrs.forEach(System.out::println);
}

TA貢獻1943條經驗 獲得超7個贊
嘗試這個。 已編輯:添加了代碼注釋。
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the code you want to check: ");
String input = scan.next();
scan.close();
List<String> codes = new ArrayList<>();
codes.add("ABC(Q,E,1)EEE");
codes.add("ABDCE(E,Z,X)E");
codes.add("B(A,1)AAEEE");
codes.add("R(1,2,3,4,5)RT(U,M,N,B,V,H)(Q,E,R,F,G,H)(R,Z)");
codes.add("B(A,1)AA(E,Z)EE");
for (Iterator<String> i = codes.iterator(); i.hasNext();) {
String code = i.next();
List<String> codePossiblity = generatePossibilities(code);
// check if the input is in the list of all the possibility
for (String s : codePossiblity) {
if (s.contains(input)) {
System.out.println("True: This code is present");
}
}
}
}
/* This method removes the parenthesis and generates all the possibilities.
* This method assumes that the parenthesis always comes in pair, thus
* for every opening parenthesis ["("] there is a closing parenthesis [")"]
* Example if the "code" is [A(WX)C(YZ)] then it will generate AWCY, AWCZ, AXCY and AXCZ
*
* @param code - The string which contains parenthesis.
* @return a list of all the possibilities
*/
public static List<String> generatePossibilities(String code) {
// This will hold the left part of the possibleCodes (part before "(")
List<String> possibleCodeList = new LinkedList<>();
String s = code;
boolean first = true;
// Loop while an open parenthesis ["("] can be found
while (s.contains("(")) {
// Retrieve from the string the first substring where "(" starts and ends with ")"
// In the example, in the first iteration will be "WX"
// in the second iteration this will be "YZ"
String inside = s.substring(s.indexOf("(") + 1, s.indexOf(")"));
// Retrieve the list inside the "(" and ")"
// In the example, in the first iteration the list will have "W", "X"
// in the second iteration the list will have "Y", "Z"
String[] listOfChoices = inside.split(",");
// This will hold the right part of the possibleCodes (part after ")")
List<String> listOfCombinations = new LinkedList<>();
// Loop all the possible choices
for (String choice : listOfChoices) {
// If it is the first iteration then you need to include those characters before the "("
if (first) {
// add the characters before the "(" and the remaining characters after ")"
// In the example, the first iteration of this list ("W", "X") will add "AWC(YZ)"
// the second iteration of this list ("W", "X") will add "AXC(YZ)"
listOfCombinations.add(s.substring(0, s.indexOf("(")) + choice + s.substring(s.indexOf(")") + 1));
}
// Else just start with choice
else {
// add the remaining characters after ")"
// In the example, the first iteration of this list ("Y", "Z") will add "Y"
// the second iteration of this list ("Y", "Z") will add "Z"
listOfCombinations.add(choice + s.substring(s.indexOf(")") + 1));
}
}
// Remove the subtring before the ")", in the example this will be "C(YZ)"
s = s.substring(s.indexOf(")") + 1);
// If it is the first iteration then you just need to assign the listOfCombinations directly to possibleCodeList,
// since possibleCodeList is still empty
if (first) {
possibleCodeList = listOfCombinations;
first = false;
}
// Else combine the left and right part
else {
List<String> codePossiblity2 = new LinkedList<>();
// Iterate though all the list of possible codes since we want all the elements in the list to be concatenated with the right half of the string
// The list will have "AWC(YZ)" and "AXC(YZ)"
for (String possibleCodes : possibleCodeList) {
// Iterate the possible combinations of the right half of the original string (the second pair of "()")
// The list will have "Y" and "Z"
for (String sTmp : listOfCombinations) {
// Replace the string which are inside the "()" in the left half of the original string.
// Replace it with the right half of the original string
// In the string of "AWC(YZ)" replace "(YZ)" with "Y"
// In the string of "AWC(YZ)" replace "(YZ)" with "Z"
// In the string of "AXC(YZ)" replace "(YZ)" with "Y"
// In the string of "AXC(YZ)" replace "(YZ)" with "Z"
String t = possibleCodes.replace("(" + inside + ")", sTmp);
// add the newly created string to codePossiblity2
codePossiblity2.add(t);
}
// At the end of the loop above codePossiblity2 will have these values
// AWCY, AWCZ, AXCY and AXCZ
}
// overwrite the possibleCodeList since we have now a new left part of the string
possibleCodeList = codePossiblity2;
}
}
return possibleCodeList;
}
}
添加回答
舉報