I have a variable requestID which i have to replace with null value.
Can anyone help me with the suitable regex for below string patterns. Eg- requestID="DEABCD-1196745-000214557" requestID="0195789_ledabj_6156096"
CodePudding user response:
You could use [A-Z-a-z0-9] (?:[_-][A-Z-a-z0-9] )
:
List<String> inputs = Arrays.asList(new String[] { "DEABCD-1196745-000214557",
"0195789_ledabj_6156096",
"BANANAS" });
for (String input : inputs) {
if (input.matches("[A-Z-a-z0-9] (?:[_-][A-Z-a-z0-9] ) ")) {
System.out.println("MATCH: " input);
}
else {
System.out.println("NO MATCH: " input);
}
}
This prints:
MATCH: DEABCD-1196745-000214557
MATCH: 0195789_ledabj_6156096
NO MATCH: BANANAS
CodePudding user response:
Would /[\w|-] /
cover what you need?
CodePudding user response:
you can try & test your Regex via online tools such as Regex101, Regexr
CodePudding user response:
This might help, try the following regex:
"([A-Z] -\\d -\\d |\\d _[a-z] _\\d )"
Regex in context and testbench:
public static void main(String[] args) {
String requestID_1 = "DEABCD-1196745-000214557";
String requestID_2 = "0195789_ledabj_6156096";
Matcher matcher1 = Pattern.compile("([A-Z] -\\d -\\d |\\d _[a-z] _\\d )").matcher(requestID_1);
if (matcher1.find()) {
requestID_1 = null;
System.out.println("Variable requestID_1 is set to: " requestID_1);
}
Matcher matcher2 = Pattern.compile("([A-Z] -\\d -\\d |\\d _[a-z] _\\d )").matcher(requestID_2);
if (matcher2.find()) {
requestID_2 = null;
System.out.println("Variable requestID_2 is set to: " requestID_2);
}
}
Output:
Variable requestID_1 is set to: null
Variable requestID_2 is set to: null