2

This is my Java code:

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a = in.nextLine();

String pattern = "^co[a-z|A-Z]e$";

String b = a.replaceAll(pattern,"1");
System.out.print(b);

I just had to replace the word "code" or any word with "co'[a-z|A-Z]'e" with '1', but it seems to work only when the input string is "code" and nothing else

Example Input: codexxccope

Expected Output: 1xxc1

My Output: codexxccope

Example Input 2: code

My Output: 1

Any suggestions?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
S4rt-H4K
  • 109
  • 6

1 Answers1

3

There are two issues here: ^ matches the start of string position, $ matches the end of string position, and [a-z|A-Z] matches any ASCII letter or | (as the pipe inside the character class matches the literal | char.

Use

String pattern = "co[a-zA-Z]e";

The [a-zA-Z] character class matches any ASCII letter.

See the regex demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563