子表达式 “[ ]” 匹配括号中指定的所有字符。因此,要将所有大写字母移动到字符串的末尾,需要执行以下步骤:
遍历给定字符串中的所有字符。
使用正则表达式 [a-z] 匹配给定字符串中的所有大写字母。
将特殊字符和剩余字符连接到两个不同的字符串中。
最后,将特殊字符字符串连接到另一个字符串中。
示例 1public 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
示例 2下面是使用 regex 包的方法将字符串的大写字母移动到末尾的 java 程序。
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); //creating a pattern object pattern pattern = pattern.compile(regex); //matching the compiled pattern in the string matcher matcher = pattern.matcher(input); //creating an empty string buffer 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 betweenresult:sample text with upper case characters in betweenbcglm
以上就是使用java正则表达式将所有大写字母移动到字符串的末尾的详细内容。