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

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

Related

How to remove every sequence of "()" in a string in java?

I'm trying to remove every sequence of () in my string.
For example my String is:
String a = "() a)";
And I want it to become
" a)"
When I tried this it gave me an infinite loop
public static String removeParentheses(String s) {
while (s.contains("()")) {
s = s.replaceAll("()", "");
}
return s;
}
String replaceAll method require regexp in parameter. In your case you provide empty group. To use string as parameter you can use replace method like:
public static void main(String[] args) {
String toChange = "asa()assaa()ass()asa()";
String result = toChange.replace("()", "");
assert Objects.equals(result, "asaassaaassasax");
}
Or change the regexp to correct form using \ character in way:
public static void main(String[] args) {
String toChange = "asa()assaa()ass()asa()";
String result = toChange.replaceAll("\\(\\)", "");
assert Objects.equals(result, "asaassaaassasax");
}
According the documentation of String.replaceAll, the first argument is a regular expression.
This means () is not being treated literally, it's being treated as an empty capture group, which effectively matches nothing. I think what you're looking for is the normal String.replace method. I'm aware that the names of these methods seem to imply that replace only replaces one instance while replaceAll replaces all of them, but this is not the case.
public static String removeParentheses(String s) {
return s.replace("()", "");
}
JDoodle deomonstrating code above
If for some reason you would like to continue using replaceAll instead, you can dynamically escape the pattern using Pattern.quote.
public static String removeParentheses(String s) {
String pattern = Pattern.quote("()");
return s.replaceAll(pattern, "");
}
JDoodle demonstrating code above

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());
}
}

Why isn't java.util.regex.matcher not matching all instances in this string?

I have the following code: http://ideone.com/mFUaqG
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegexUtils
{
private static final Pattern resourceURLCSS = Pattern.compile("url\\([\'\"](((?!://).)*)[\'\"]\\)");
private static final Pattern resourceURLHTML = Pattern.compile("(href|src|url)=[\'\"](((?!://).)*)[\'\"]");
public static String makeCSSURLsAbsolute(String input, String baseURL)
{
Matcher matcher = resourceURLCSS.matcher(input);
return matcher.replaceAll("url('"+baseURL+"$1')");
}
public static String makeHTMLURLsAbsolute(String input, String baseURL)
{
Matcher matcher = resourceURLHTML.matcher(input);
return matcher.replaceAll("$1=\""+baseURL+"$2\"");
}
public static void main(String[] args)
{
String fixed = RegexUtils.makeCSSURLsAbsolute("div#header { background-image: url('images/header-background.jpg'); } div#header { background-image: url('images/header-background.jpg'); }", "http://www.google.ca/");
System.out.println(fixed);
fixed = RegexUtils.makeHTMLURLsAbsolute("href=\"wtfguys.css\" href=\"wtfguys.css\"", "http://www.google.ca/");
System.out.println(fixed);
}
}
Unfortunately, this code doesn't do what I expect, which is to replace all occurrences of the regular expression with the string replacement. We are essentially replacing relative URLs in CSS and HTML with absolute URLS. It only seems to replace the first occurrence, giving
div#header { background-image: url('http://www.google.ca/images/header-background.jpg'); } div#header { background-image: url('images/header-background.jpg'); }
href="http://www.google.ca/wtfguys.css" href="wtfguys.css"
as output. Any suggestions?
You are using regexps that attempt to match both single- and double quoted attribute values. The thing is, you may match a truncated value because none of the two patterns makes sure the opening quote matches the closing. Also, that quote should be missing in the value itself.
So, wrap the opening quote into a capture group, use a backrefrence as the closing delimiter and add the backrefrence as an alternative to the lookahead in the tempered greedy token. Then, fix the replacement patterns since the order of backreferences will change.
private static final Pattern resourceURLCSS = Pattern.compile("url\\((['\"])((?:(?!://|\\1).)*)\\1\\)");
private static final Pattern resourceURLHTML = Pattern.compile("(href|src|url)=(['\"])((?:(?!://|\\2).)*)\\2");
public static String makeCSSURLsAbsolute(String input, String baseURL)
{
Matcher matcher = resourceURLCSS.matcher(input);
return matcher.replaceAll("url('"+baseURL+"$2')");
}
public static String makeHTMLURLsAbsolute(String input, String baseURL)
{
Matcher matcher = resourceURLHTML.matcher(input);
return matcher.replaceAll("$1=\""+baseURL+"$3\"");
}
See the IDEONE demo
.* is greedy. The matcher captures wtfguys.css" href="wtfguys.css as $2, not wtfguys.css. You can use .*? or [^\"]* instead, since URLs don't have even escaped quotes inside. Reference for this issue explaining several options (including the one mentioned by Wiktor): http://www.rexegg.com/regex-quantifiers.html#greedytrap.

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(".*\\[|].*", ""));
}

Java check that string will only allow commas as special chacters

how can I check to make sure the only special character a string can have is a comma?
testString = "123,34565,222" //OK
testString = "123,123.123." //Fail
A full working example based on #Simeon's regex. This reuses a single Matcher object, which is recommended if the check will be done frequently.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class OnlyLettersDigitsCommas {
//"": Dummy search string, to reuse matcher
private static final Matcher lettersCommasMtchr = Pattern.
compile("^[a-zA-Z0-9,]+$").matcher("");
public static final boolean isOnlyLettersDigitsCommas(String to_test) {
return lettersCommasMtchr.reset(to_test).matches();
}
public static final void main(String[] ignored) {
System.out.println(isOnlyLettersDigitsCommas("123,34565,222"));
System.out.println(isOnlyLettersDigitsCommas("123,123.123."));
}
}
Output:
[C:\java_code\]java OnlyLettersDigitsCommas
true
false
You can use a quick String.contains method like this:
if ( testString.contains(".") {
// fails
}
But I would consider using Regex for this type of validation.
EDIT : As stated in the comments of the question : [a-zA-Z0-9,]
Maybe a
if (!testString.matches("^[a-zA-Z0-9,]+$")) {
// throw an exception
}
check ?

Categories

Resources