Home > Blockchain >  Java regex to find (plus sign) with characters
Java regex to find (plus sign) with characters

Time:11-17

With java regex i want to find the word "C " and it should not be positive with only "C".

The below code should explain the rest, see here

import java.util.*;
import java.util.regex.*;
public class MyClass {
public static void main(String args[]) {
  
  String test = "Framework, c   and Visual Studio IDEs.";
  Pattern p = Pattern.compile("(?i).*\\bc\\ \\ \\b.*");
  Matcher m = p.matcher(test);
    if(m.find()) {
        System.out.println("Pattern1 True");
    }
  p = Pattern.compile("(?i).*\\Bc. . \\B.*");
  m = p.matcher(test);
    if(m.find()) {
        System.out.print("Pattern2 True");
    }
    p = Pattern.compile("(?i).*\\bc $\\b.*");
  m = p.matcher(test);
    if(m.find()) {
        System.out.println("Pattern3 is True but how to return false");
    }
    p = Pattern.compile("(?i).*\\Bc\\B.*");
  m = p.matcher(test);
    if(m.find()) {
        System.out.println("Pattern4 is True");
    }
  if(test.toLowerCase()   .contains("c  ")) {
        System.out.print("Contains c   True");
  }
  if(test.toLowerCase().contains("C")) {
        System.out.print("Contains C True");
  }
}
}

CodePudding user response:

You can use

Pattern p = Pattern.compile("(?i).*\\bc\\ \\ \\B.*");     // C  
Pattern p = Pattern.compile("(?i).*\\bC\\b(?!\\ {2}).*"); // C only

Here,

  • \b - a word boundary
  • c\ \ - a c string
  • \B - a non-word boundary, on the right, there must be end of string or a non-word char
  • (?!\ {2}) - a negative lookahead that fails the match if there is a string immediately to the right of the current location.

CodePudding user response:

This seems to work at detecting either "C " or "c " anywhere in an input string.

String regex = ".*[cC]\\ \\ .*";
java.util.regex.Pattern.matches(regex, "This is NOT c   !");

Results in true, but

java.util.regex.Pattern.matches(regex, "This is NOT c!");

results in false.

CodePudding user response:

tough time omitting characters for only C

p = Pattern.compile("(?i).*\\bC\\b(?!\\ |#|\\$|\\*|\\^|%|&).*");
  m = p.matcher(test);
    if(m.find()) {
        System.out.println("C is true");
    }
    p = Pattern.compile("(?i).*\\bc\\ \\ \\B.*");
  m = p.matcher(test);
    if(m.find()) {
        System.out.println("C   is true");
    }
    p = Pattern.compile("(?i).*\\bc\\#\\B.*");
  m = p.matcher(test);
    if(m.find()) {
        System.out.println("C# is true");
    }
  • Related