Is there 'stoi()' like thing in Java? - 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());
}
}

Related

Need to check wildcard characters using regex

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

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;

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 ?

How to iterate over regexp compliant strings

What is the easiest way to implement a class (in Java) that would serve as an iterator over the set of all values which conform to a given regexp?
Let's say I have a class like this:
public class RegexpIterator
{
private String regexp;
public RegexpIterator(String regexp) {
this.regexp = regexp;
}
public abstract boolean hasNext() {
...
}
public abstract String next() {
...
}
}
How do I implement it? The class assumes some linear ordering on the set of all conforming values and the next() method should return the i-th value when called for the i-th time.
Ideally the solution should support full regexp syntax (as supported by the Java SDK).
To avoid confusion, please note that the class is not supposed to iterate over matches of the given regexp over a given string. Rather it should (eventually) enumerate all string values that conform to the regexp (i.e. would be accepted by the matches() method of a matcher), without any other input string given as argument.
To further clarify the question, let's show a simple example.
RegexpIterator it = new RegexpIterator("ab?cd?e");
while (it.hasNext()) {
System.out.println(it.next());
}
This code snippet should have the following output (the order of lines is not relevant, even though a solution which would list shorter strings first would be preferred).
ace
abce
ecde
abcde
Note that with some regexps, such as ab[A-Z]*cd, the set of values over which the class is to iterate is ininite. The preceeding code snippet would run forever in these cases.
Do you need to implement a class? This pattern works well:
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher("123, sdfr 123kjkh 543lkj ioj345ljoij123oij");
while (m.find()) {
System.out.println(m.group());
}
output:
123
123
543
345
123
for a more generalized solution:
public static List<String> getMatches(String input, String regex) {
List<String> retval = new ArrayList<String>();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
while (m.find()) {
retval.add(m.group());
}
return retval;
}
which then can be used like this:
public static void main(String[] args) {
List<String> matches = getMatches("this matches _all words that _start _with an _underscore", "_[a-z]*");
for (String s : matches) { // List implements the 'iterable' interface
System.out.println(s);
}
}
which produces this:
_all
_start
_with
_underscore
more information about the Matcher class can be found here: http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html
Here is another working example. It might be helpful :
public class RegxIterator<E> implements RegexpIterator {
private Iterator<E> itr = null;
public RegxIterator(Iterator<E> itr, String regex) {
ArrayList<E> list = new ArrayList<E>();
while (itr.hasNext()) {
E e = itr.next();
if (Pattern.matches(regex, e.toString()))
list.add(e);
}
this.itr = list.iterator();
}
#Override
public boolean hasNext() {
return this.itr.hasNext();
}
#Override
public String next() {
return this.itr.next().toString();
}
}
If you want to use it for other dataTypes(Integer,Float etc. or other classes where toString() is meaningful), declare next() to return Object instead of String. Then you may able be to perform a typeCast on the return value to get back the actual type.

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

Categories

Resources