Java check that string will only allow commas as special chacters - java

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 ?

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

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.

Regex with two patterns

I have a requirement where in I want to get two different items form one long string.
I have got below program where in I get required items when I do group(1) and group(6).
But I want to get it in group(1) and group(2).
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[]) {
String somepattern = "((123|456)-(0|1)-((\\d-?){8})-\\d{1})/(\\d{2})";
String str = "/somethingwaste/123-0-1234-5678-9/10";
Matcher p = Pattern.compile(somepattern).matcher(str);
while (p.find()) {
System.out.println(p.group(1));
System.out.println(p.group(6));
}
Any pointers directions appriciated.
Thanks
This should do it
String somepattern = "((?:123|456)-[01]-(?:\\d-?){8}-\\d)/(\\d{2})";
The ?: makes a () non-capturing.
Just make the groups you don't want to keep non-capturing using ?::
String somepattern = "((?:123|456)-[01]-(?:\\d-?){8}-\\d)/(\\d{2})";
String str = "/somethingwaste/123-0-1234-5678-9/10";
Matcher p = Pattern.compile(somepattern).matcher(str);
while (p.find()) {
System.out.println(p.group(1));
System.out.println(p.group(2));
}

avoid code duplication

consider the following code:
if (matcher1.find()) {
String str = line.substring(matcher1.start()+7,matcher1.end()-1);
/*+7 and -1 indicate the prefix and suffix of the matcher... */
method1(str);
}
if (matcher2.find()) {
String str = line.substring(matcher2.start()+8,matcher2.end()-1);
method2(str);
}
...
I have n matchers, all matchers are independent (if one is true, it says nothing about the others...), for each matcher which is true - I am invoking a different method on the content it matched.
question: I do not like the code duplication nor the "magic numbers" in here, but I'm wondering if there is better way to do it...? (maybe Visitor Pattern?) any suggestions?
Create an abstract class, and add offset in subclass (with string processing too... depending of your requirement).
Then populate them in a list and process the list.
Here is a sample absract processor:
public abstract class AbsractProcessor {
public void find(Pattern pattern, String line) {
Matcher matcher = p.matcher(line);
if (matcher.find()) {
process(line.substring(matcher.start() + getStartOffset(), matcher.end() - getEndOffset()));
}
}
protected abstract int getStartOffset();
protected abstract int getEndOffset();
protected abstract void process(String str);
}
Simple mark the part of the regex that you want to pass to the method with a capturing group.
For example if your regex is foo.*bar and you are not interested in foo or bar, make the regex foo(.*)bar. Then always grab the group 1 from the Matcher.
Your code would then look like this:
method1(matcher1.group(1));
method2(matcher2.group(2));
...
One further step would be to replace your methods with classes implementing an like this:
public interface MatchingMethod {
String getRegex();
void apply(String result);
}
Then you can easily automate the task:
for (MatchingMethod mm : getAllMatchingMethods()) {
Pattern p = Pattern.compile(mm.getRegex());
Matcher m = p.matcher(input);
while (m.find()) {
mm.apply(m.group(1));
}
Note that if performance is important, then pre-compiling the Pattern can improve runtime if you apply this to many inputs.
You could make it a little bit shorter, but I the question is, is this really worth the effort:
private String getStringFromMatcher(Matcher matcher, int magicNumber) {
return line.subString(matcher.start() + magicNumber, matcher.end() - 1 )
}
if (matcher1.find()) {
method1(getStringFromMatcher(matcher1, 7);
}
if (matcher2.find()) {
method2.(getStringFromMatcher(mather2, 8);
}
use Cochard's solution combined with a factory (switch statement) with all the methodX methods. so you can call it like this:
Factory.CallMethodX(myEnum.MethodX, str)
you can assign the myEnum.MethodX in the population step of Cochard's solution

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