সাব-এক্সপ্রেশন "[ ]" ব্রেস-এ নির্দিষ্ট সমস্ত ক্যারেক্টার মিলাতে ব্যবহৃত হয়। তাই, একটি স্ট্রিং-এ থাকা সব বড় হাতের অক্ষর (Upper case letters) শেষে নিয়ে যেতে:
- দেওয়া স্ট্রিং-এ থাকা সব ক্যারেক্টারসহ.Iterate করুন।
- রেগুলার এক্সপ্রেশন
"[A-Z]"ব্যবহার করে স্ট্রিং-এ থাকা সব বড় হাতের অক্ষর মিলান। - বিশেষ ক্যারেক্টার এবং বাকি ক্যারেক্টারগুলোকে দুটি আলাদা স্ট্রিং-এ কনক্যাটেনেট করুন।
- শেষে, বিশেষ ক্যারেক্টার স্ট্রিংটি অন্য স্ট্রিং-এর সাথে কনক্যাটেনেট করুন।
উদাহরণ ১
public class RemovingSpecialCharacters {
public static void main(String args[]) {
String input = "sample B text C with G upper case LM characters in between";
String regex = "[A-Z]";
String specialChars = "";
String inputData = "";
for(int i=0; i< input.length(); i++) {
char ch = input.charAt(i);
if(String.valueOf(ch).matches(regex)) {
specialChars = specialChars + ch;
} else {
inputData = inputData + ch;
}
}
System.out.println("Result: " + inputData + specialChars);
}
}
আউটপুট
Result: sample text with upper case characters in betweenBCGLM
উদাহরণ ২
নিচের জাভা প্রোগ্রামটি Regex প্যাকেজের মেথডগুলো ব্যবহার করে একটি স্ট্রিং-এ থাকা বড় হাতের অক্ষরগুলোকে তার শেষে নিয়ে যায়।
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) {
String input = "sample B text C with G upper case LM characters in between";
String regex = "[A-Z]";
String specialChars = "";
System.out.println("Input string: \n" + input);
// Pattern অবজেক্ট তৈরি
Pattern pattern = Pattern.compile(regex);
// স্ট্রিং-এ কম্পাইল করা প্যাটার্ন মিলানো
Matcher matcher = pattern.matcher(input);
// খালি একটি স্ট্রিং বাফার তৈরি
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
specialChars = specialChars + matcher.group();
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("Result: \n" + sb.toString() + specialChars);
}
}
আউটপুট
Input string: sample B text C with G upper case LM characters in between Result: sample text with upper case characters in betweenBCGLM