নিচের রেগুলার এক্সপ্রেশনটি সমস্ত বিশেষ ক্যারেক্টার মিলায় অর্থাৎ ইংরেজি বর্ণমালা, স্পেস এবং সংখ্যা ব্যতীত সব ক্যারেক্টার।
"[^a-zA-Z0-9\\s+]"
দেওয়া লাইন-এ থাকা সব বিশেষ ক্যারেক্টার এই রেগেক্স দিয়ে মিলিয়ে একটি খালি স্ট্রিং-এ কনক্যাটেনেট করুন এবং বাকি ক্যারেক্টারগুলো অন্য একটি স্ট্রিং-এ কনক্যাটেনেট করুন। শেষে এই দুটি স্ট্রিংকে একসাথে কনক্যাটেনেট করুন।
উদাহরণ ১
public class RemovingSpecialCharacters {
public static void main(String args[]) {
String input = "sample # text * with & special@ characters";
String regex = "[^a-zA-Z0-9\\s+]";
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 special characters#*&@
উদাহরণ ২
নিচের জাভা প্রোগ্রামটি Regex প্যাকেজের মেথডগুলো ব্যবহার করে একটি স্ট্রিং-এ থাকা বিশেষ ক্যারেক্টারগুলোকে তার শেষে নিয়ে যায়।
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) {
String input = "sample # text * with & special@ characters";
String regex = "[^a-zA-Z0-9\\s+]";
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 # text * with & special@ characters Result: sample text with special characters#*&@