I have a question:
int index = abc.indexOf("def"||"ghi");
I tried the code above to search "def" or "ghi" in a String "abc". But this doesn't work. There's the error "Operator || cannot be applied to 'java.lang.String', 'java.land.String'".
How can I solve the problem?
As the compiler has stated, the || conditional operator is being used incorrectly there.
this is what you want:
int index = abc.contains("def") ? abc.indexOf("def"):
abc.contains("ghi")? abc.indexOf("ghi"): -1;
if(index != -1 ){
//do someting
}
int index = abc.indexOf("def");
if (index == -1) {
index = abc.indexOf("ghi");
} else {
// something else
}
You can also achieve it using the Matcher class as follows:
Pattern pattern = Pattern.compile("(def)|(ghi)");
Matcher matcher = pattern.matcher(abc);
int index;
if (matcher.find()) {
index = matcher.start();
} else {
index = -1;
}
Basically you compile a certain regex pattern that matches the sequence you want to match. matcher.find() will look for the first occurrence of the pattern and if it finds, you can use matcher.start() to get the start index of the matched pattern.
Related
I want to restrict getGatewaySerialNumber from taking special characters.
I have written these condition but if block it is executing only first condition it is not checking for and condition.
How to restrict Gatewayserialnumber from taking special character.
If(manifestRequestEntity.getGatewaySerialNumber().lenghth()>16 && manifestRequestEntity.getGatewaySerialNumber().matches(regex :"[0-9a-fA-F]+"))
You can use some helper methods to check if it only contains alphabets and numbers
something like this :
public static boolean checkForSpecialChar(String stringToCheck){
char ch[] = stringToCheck.toCharArray();
for(int i=0; i<ch.length; i++)
{
if((ch[i]>='A' && ch[i]<='Z') || (ch[i]>='a' && ch[i]<='z') || (ch[i]>='0' && ch[i]<='9'))
{
continue;
}
return true;
}
return false;
}
Try This.
name = "abc";
Pattern special= Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Pattern number = Pattern.compile("[0-9]", Pattern.CASE_INSENSITIVE);
Matcher matcher = special.matcher(name);
Matcher matcherNumber = number.matcher(name);
boolean constainsSymbols = matcher.find();
boolean containsNumber = matcherNumber.find();
if(constainsSymbols){
//string contains special symbol/character
}
else if(containsNumber){
//string contains numbers
}
else{
//string doesn't contain special characters or numbers
}
I have a string which consists of total n equal substrings. For example, string "hellooo dddd" has 3 "dd" substrings (I say it has occured 3 times). In a more general case which we have n equal substrings in a string, how can I replace i-th occurance in the string. A ,method like replace() for i-th substring. I want to implement it in my android code. (English isn’t my first language, so please excuse any mistakes.).
public static String replace(String input, String pattern, int occurence, String replacement){
String result = input;
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(result);
if(occurence == 0){
return result;
} else if(occurence == 1){
m.find();
result = result.substring(0,m.start()) + replacement + result.substring(m.end());
} else {
m.find();
int counter = 1;
try {
while((counter<occurence)&&m.find(m.start()+1)){
counter++;
}
result = result.substring(0,m.start()) + replacement + result.substring(m.end());
} catch(IllegalStateException ise){
throw new IllegalArgumentException("There are not this many occurences of the pattern in the String.");
}
}
return result;
}
Seems to do something similar to what you want if I understand correctly.
Using the matcher/pattern system it's open to much more complex regex.
I want to find a single regex which matches the longest numerical string in a URL.
I.e for the URL: http://stackoverflow.com/1234/questions/123456789/ask, I would like it to return : 123456789
I thought I could use : ([\d]+)
However this returns the first match from the left, not the longest.
Any ideas :) ?
This regex will be used as an input to a strategy pattern, which extracts certain characteristics from urls:
public static String parse(String url, String RegEx) {
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(url);
if (m.find()) {
return m.group(1);
}
return null;
}
So it would be much tidier if I could use a single regex. :( –
Don't use regex. Just iterate the characters:
String longest = 0;
int i = 0;
while (i < str.length()) {
while (i < str.length() && !Character.isDigit(str.charAt(i))) {
++i;
}
int start = i;
while (i < str.length() && Character.isDigit(str.charAt(i))) {
++i;
}
if (i - start > longest.length()) {
longest = str.substring(start, i);
}
}
#Andy already gave a non-regex answer, which is probably faster, but if you want to use regex, you must, as #Jan points out, add logic, e.g.:
public String findLongestNumber(String input) {
String longestMatch = "";
int maxLength = 0;
Matcher m = Pattern.compile("([\\d]+)").matcher(input);
while (m.find()) {
String currentMatch = m.group();
int currentLength = currentMatch.length();
if (currentLength > maxLength) {
maxLength = currentLength;
longestMatch = currentMatch;
}
}
return longestMatch;
}
t
Not possible with pure Regex, however I would do it this way (using Stream Max and Regex) :
String url = "http://stackoverflow.com/1234/questions/123456789/ask";
Pattern biggest = Pattern.compile("/(\\d+)/");
Matcher m = biggest.matcher(url);
List<String> matches = new ArrayList<>();
while(m.find()){
matches.add(m.group(1));
}
System.out.println(matches.parallelStream().max((String a, String b) -> Integer.compare(a.length(), b.length())).get());
Will print : 123456789
I have a list and I want to get the position of the string which starts with specific letter.
I am trying this code, but it isn't working.
List<String> sp = Arrays.asList(splited);
int i2 = sp.indexOf("^w.*$");
The indexOf method doesn't accept a regex pattern. Instead you could do a method like this:
public static int indexOfPattern(List<String> list, String regex) {
Pattern pattern = Pattern.compile(regex);
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
if (s != null && pattern.matcher(s).matches()) {
return i;
}
}
return -1;
}
And then you simply could write:
int i2 = indexOfPattern(sp, "^w.*$");
indexOf doesn't accept a regex, you should iterate on the list and use Matcher and Pattern to achieve that:
Pattern pattern = Pattern.compile("^w.*$");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.print(matcher.start());
}
Maybe I misunderstood your question. If you want to find the index in the list of the first string that begins with "w", then my answer is irrelevant. You should iterate on the list, check if the string startsWith that string, and then return its index.
I was given a long text in which I need to find all the text that are embedded in a pair of & (For example, in a text "&hello&&bye&", I need to find the words "hello" and "bye").
I try using the regex ".*&([^&])*&.*" but it doesn't work, I don't know what's wrong with that.
Any help?
Thanks
Try this way
String data = "&hello&&bye&";
Matcher m = Pattern.compile("&([^&]*)&").matcher(data);
while (m.find())
System.out.println(m.group(1));
output:
hello
bye
No regex needed. Just iterate!
boolean started = false;
List<String> list;
int startIndex;
for(int i = 0; i < string.length(); ++i){
if(string.charAt(i) != '&')
continue;
if(!started) {
started = true;
startIndex = i + 1;
}
else {
list.add(string.substring(startIndex, i)); // maybe some +-1 here in indices
}
started = !started;
}
or use split!
String[] parts = string.split("&");
for(int i = 1; i < parts.length; i += 2) { // every second
list.add(parts[i]);
}
If you don't want to use regular expressions, here's a simple way.
String string = "xyz...." // the string containing "hello", "bye" etc.
String[] tokens = string.split("&"); // this will split the string into an array
// containing tokens separated by "&"
for(int i=0; i<tokens.length; i++)
{
String token = tokens[i];
if(token.length() > 0)
{
// handle edge case
if(i==tokens.length-1)
{
if(string.charAt(string.length()-1) == '&')
System.out.println(token);
}
else
{
System.out.println(token);
}
}
}
Two problems:
You're repeating the capturing group. This means that you'll only catch the last letter between &s in the group.
You will only match the last word because the .*s will gobble up the rest of the string.
Use lookarounds instead:
(?<=&)[^&]+(?=&)
Now the entire match will be hello (and bye when you apply the regex for the second time) because the surrounding &s won't be part of the match any more:
List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("(?<=&)[^&]+(?=&)");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}
The surrounding .* don't make sense and are unproductive. Just &([^&])*& is sufficient.
I would simplify it even further.
Check that the first char is &
Check that the last char is &
String.split("&&") on the substring between them
In code:
if (string.length < 2)
throw new IllegalArgumentException(string); // or return[], whatever
if ( (string.charAt(0) != '&') || (string.charAt(string.length()-1) != '&')
// handle this, too
String inner = string.substring(1, string.length()-1);
return inner.split("&&");