Need to check wildcard characters using regex - java

i am checking not allowed charters from input string
protected static Boolean validateWildcardCharacters(String inputText) {
List<String> term = Arrays.asList("!","#","#","$","%","^","&","(",")","_","+","=",";",";","{","}","[","]","'","<",">",",",".","|");
Boolean containChar = false;
for(String ch : term){
if(inputText.contains(ch)) {
containChar = true;
break;
}
};
return containChar;
But I am looking for some better solution. Maybe using Regular expression (regex).
please suggest better approach to do that.
Thanks

If you want to use a regular expression, you need to use the Pattern and Matcher classes from java.util.regex. Here is an example on how you could use it:
public static final String EXAMPLE_TEST = "Your string here : { } . / []";
public static void main(String[] args) {
Pattern pattern = Pattern.compile("[!##$%^&*(),.?\":{}|<>\\[\\]]");
Matcher matcher = pattern.matcher(EXAMPLE_TEST);
if (matcher.find())
System.out.println("found");
else {
System.out.println("not found");
}
}

Related

Is there 'stoi()' like thing in Java?

I'm new to Java, I'm looking for a stoi()-like function in Java which is in C++.
I want like this:
If there is string like "123ABC", I want extract '123' in Integer and get the index of 'A'.
I've been looking for this, but I couldn't find it. So I upload it here.
In advance, really thank you so much who help me!
Use NumberFormat#parse(String, ParsePosition). The first argument would be "123ABC", the return value will be 123 and the ParsePosition points to A.
You can try following code:
public class Number {
public static void main(String[] args) {
String str = "A1234BCD";
extractDigit(str);
}
public static void extractDigit(String str){
str="A1234AB2C";
String numberOnly= str.replaceAll("[^0-9]", "");
System.out.println(numberOnly);
Pattern pattern = Pattern.compile("\\p{L}");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println(matcher.start());
}
}

How to use Matches() and Pattern correctley

I'm doing a assignment for school and need to build a Student class. The constructor will receive a String,"Student name". I need to verify that the given String from the user includes only letters from a-z, A-Z, and numbers 0-9.
From looking online this is what I found
boolean ans = true;
String str = ("Maor Rocky");
Pattern pattern = Pattern.compile("[A-Za-z0-9]\\w+");
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.group());
if (!str.matches("[a-zA-Z0-9//s+]"))
ans = false;
System.out.println(ans);
I know it's missing something but I didn't grasp the idea of pattern and matcher yet.
thanks every one, this is the code i wrote and it works:
boolean ans = true;
if (!name.matches("^[a-zA-Z0-9 ]+$")) {
ans = false;
You need something like that:
public class Student {
private String name;
public Student(String name) throws IllegalArgumentException {
if (!name.matches("[\\w]*")) {
throw new IllegalArgumentException("name should contain only alphanumeric chars.");
}
this.name = name;
}
public String getName() {
return name;
}
}
If you have variable student of type String that will hold student name, simple check goes like this (no need to use Pattern or Matcher classes here):
String student = scanner.next();
if (student.matches("[\\w]*"))
//do something for valid username
else
//do something for invalid username
Or do it the same way every beginner would do it:
String student = scanner.next();
for (int i = 0; i < student.length(); i++) {
if (!Character.isLetterOrDigit(student.charAt(i)))
//do something for invalid username;
}
To understand the uses of Matcher you should see This link
In this example the Matcher and Pattern objects aren't doing anything because you are using a String method that works with regexp. If you wanted to use the Matcher your if would look something like this
if(matcher.matches())
ans=false;

Is there an elegant way to get fist two consecutive characters from a String until fist digit occurrence

I want to get the fist two characters (not digits) from a String until the first digit occurance. String may be any and would contains digits too. I just have to care first two indexes only. Bit tricky part is let say the second index contains a digit, then only the first character need to consider.
Examples:
abcd -> ab
a -> a
a0cd -> a
0bcd -> null
-123 -> null
Below is how I wrote this function in java. Is there any other elegant way to do this? Any help is much appreciated.
public class Main {
public static String getFirstTwoCharBeforeDigit(String s) {
if(null==s||s.length()==0) return null;
int cropIndex=Math.min(s.length(), 2);
if(!Character.isLetter(s.charAt(0))) return null;
if(cropIndex>1 && !Character.isLetter(s.charAt(1))) --cropIndex;
return s.substring(0,cropIndex);
}
public static void main(String[] args) {
System.out.println(getFirstTwoCharBeforeDigit("Az-a0"));
}
}
This seems to work (thank you Timothy):
private static final java.util.regex.Pattern pattern = Pattern.compile("^[a-z]{1,2}");
private static String getFirstTwoChars(String string) {
if (string == null) {
return null;
}
java.util.regex.Matcher matcher = pattern.matcher(string);
return matcher.find() ? matcher.group(0) : null;
}
I'd suggest the use of regular expressions as described in the API of the Pattern class.
"^[a-z]{1,2}"
#RunWith(Parameterized.class)
public class ConsecutiveCharsTest {
#Parameters
public static Collection<Object[]> data() {
//#formatter:off
return Arrays.asList(new Object[][] {
{"abcd", "ab" },
{"a", "a" },
{"a0bc", "a" },
{"0bcd", null },
{"-123", null },
});
//#formatter:on
}
private final String input;
private final String expected;
public ConsecutiveCharsTest(String input, String expected) {
super();
this.input = input;
this.expected = expected;
}
#Test
public void test() {
Pattern pattern = Pattern.compile("^[a-z]{1,2}");
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
assertEquals(input, expected, matcher.group());
} else {
assertNull("no Match expected", expected);
}
}
}
I think that using RegExp for this simple task is too heavy, because lot's of additional objects are created behind the scene. My solution is less readable, but it has better performance and minimal additional memory objects creation:
public static String getFirstTwoCharBeforeDigit(String str) {
return str != null && !str.isEmpty() ? Character.isAlphabetic(str.charAt(0)) ? str.substring(0, str.length() > 1 && Character.isAlphabetic(str.charAt(1)) ? 2 : 1) : null : null;
}
Just to add one more alternative:
public static String getFirstTwoCharBeforeDigit(String str) {
String firstTwo = str.substring(0,Math.min(str.length(), 2)).replaceAll("\\d*$", "");
return firstTwo.chars().allMatch(Character::isLetter) && !firstTwo.isEmpty()?
firstTwo:
null;
}

Java regex using pattern matcher not returning correctly?

I have to get index value from the following string:
Home.number[12].parent.
I want to get back value of 12.
Here is what I tried:
//escape . / [ ]
private static final String pattern = "Home\\.number\\[([0-9]*)\\]*";
private static final Pattern addressPattern = Pattern.compile(pattern);
private static int getIndex(String input, Pattern pattern){
Matcher m = pattern.matcher(input);
if (m.matches()){
return Integer.valueOf(m.group(2));
}
return -1;
}
public static void main(String[] args){
System.out.println(getIndex("Home.number[123].parent", addressPattern);
System.out.println(getIndex("Home.number[456].child", addressPattern);
}
I get back -1 for both, meaning no match is found.
Using the debugger, I found that m.matches() is returning false.
I am unable to figure out why.
P.S: I also tried using Pattern.quote("Home.number[([0-9]*])*") and StringUtils.EscapeJava("Home.number[([0-9]*)]*"). Both are not returning any matching results.
Your Pattern should look something like
private static final String pattern = "Home\\.number\\[(\\d+)\\]\\..*";
private static final Pattern addressPattern = Pattern.compile(pattern);
And your matcher only has 1 group.
private static int getIndex(String input, Pattern pattern) {
Matcher m = pattern.matcher(input);
if (m.matches()) {
return Integer.parseInt(m.group(1));
}
return -1;
}
And you need to close the second paren in your calls in main. Something like
public static void main(String[] args) {
System.out.println(getIndex("Home.number[123].parent", addressPattern));
System.out.println(getIndex("Home.number[456].child", addressPattern));
}
When I make those changes I get the expected
123
456
Change the pattern from: "Home\\.number\\[([0-9]*)\\]*" to "Home\\.number\\[([0-9]+)\\].*" (adding the dot before the last *)
Change the group to #1: return Integer.valueOf(m.group(1));
Add closing brackets to the System.out.println() calls.
Like this:
private static final String pattern = "Home\\.number\\[([0-9]*)\\].*";
private static final Pattern addressPattern = Pattern.compile(pattern);
private static int getIndex(String input, Pattern pattern){
Matcher m = pattern.matcher(input);
if (m.matches()){
return Integer.valueOf(m.group(1));
}
return -1;
}
public static void main( String[] args ){
System.out.println(getIndex("Home.number[123].parent", addressPattern));
System.out.println(getIndex("Home.number[456].child", addressPattern));
}
If you remove everything except what between the square brackets, you can do it in one line:
private static int getIndex(String input) {
return input.matches(".*\\[\\d+].*") ? -1 : Integer.parseInt(input.replaceAll(".*\\[|].*", ""));
}

How to validate a Geometric point using a Java Regular Expression?

I tried like this - To validate a point like x,y
"[0-9]{1,},[0-9]{1,}"
Its not working.
UPDATE:
I must be doing something wrong. This is a simple Console input through Scanner(System.in) - using Scanner#nextLine which returns a String.
private static String REGEX_PATTERN = "[0-9]{1,}[,][0-9]{1,}";
private static Pattern regExPattern = Pattern.compile(REGEX_PATTERN);
private static Matcher regExMatcher;
regExMatcher = regExPattern.matcher(getStringValue());
isValid = regExMatcher.matches();
I tried svrist's solution too. It didn't help.
It is working:
public class Test {
private static String REGEX_PATTERN = "[0-9]{1,}[,][0-9]{1,}";
private static Pattern regExPattern = Pattern.compile(REGEX_PATTERN);
private static Matcher regExMatcher;
public static void main(String[] args) {
test("1,3"); // true
test("123"); // false
test("1-3"); // false
test("123,456"); // true
test("123, 56"); // false
test(" 23,456"); // false
test("123,456\n"); // false
}
private static void test(String string) {
regExMatcher = regExPattern.matcher(string);
boolean isValid = regExMatcher.matches();
System.out.printf("\"%s\" - %s%n", string, isValid);
}
}
maybe getStringValue() is returning some extra character like white-spaces or line-feeds.
To ignore the spaces try with
REGEX_PATTERN = "\\s*\\d+\\s*,\\s*\\d+\\s*";
I think I found what you are looking for:
http://www.dreamincode.net/forums/topic/132735-coordinates-regex/
If you tried "4,5" and it doesn't work, then something else is wrong.
tjwebb#latitude:~$ rhino
Rhino 1.7 release 2 2010 09 15
js> /[0-9]{1,},[0-9]{1,}/.test("4,5");
true
For me, "4,5" does match, so you must not be using that regular expression correctly. It looks correct to me. What language are you using?
-tjw

Categories

Resources