How to use AND operator in regex for java to match 2 whole words ? i want both the words to be present

172 views Asked by At

I have 2 separate strings "TM_TASK" and "TM_CHECKLIST". How can i validate both the words in whole using regex in java ? How to use AND operator in regex for this case in java ? i need both the strings to be validated and not either of them. I am new to regex.

@Pattern(value = "(?=.*TM_TASK)(?=.*TM_CHECKLIST).*", patternType = PatternType.REGEX)  
@ApiOperation(value = "Fetch all instances of a specific checklist", produces = "application/json", response = ChecklistInstance.class, tags = "tasks")
@ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "Authorization token", required = true, dataType = "string", paramType = "header"),
        @ApiImplicitParam(name = "body", value = "json document", required = true, dataType = "json", paramType = "body") })
@BodyParser.Of(BodyParser.Json.class)
public Result getChecklistInstances() {
2

There are 2 answers

1
Chris On

RegEx:

^TM_(TASK|CHECKLIST)$

in Java:

String.matches("^TM_(TASK|CHECKLIST)$");

Find manual at RegExJava

7
marvel308 On

you can use the regex

(?=.*TM_TASK)(?=.*TM_CHECKLIST).*

to match if the string contains both TM_TASK and TM_CHECKLIST, see the regex101 demo. Once this is done you can match those words using the regex

TM_(?:TASK|CHECKLIST)

see the regex101 demo