I want to convert a string number starts with 00 to + such as 0046760963101 to +46760963101. Is there any solution to handle it via regex?
If not what solution do you recommend?
Addenda :
If it starts with 000 or more, I do not want to replace with + sign.
with regex assuming the input is a numeric string
s.replaceFirst("^00", "+")
or with regex if you aren't sure of the input format
s.replaceFirst("^00([0-9]+)$", "+$1")
or with a simple match
s.startsWith("00") ? "+"+s.substring(2) : s
Inculding the added requirement: If it starts with 000 or more, I do not want to replace with + sign.
String normalized = phone;
if ( !phone.matches("000+([0-9]+)") && phone.startsWith("00")) {
normalized = "+"+phone.substring(2);
}
Check you input in regex tester like: https://www.freeformatter.com/java-regex-tester.html#ad-output
You can try something like this
public static void main(String[] args) {
String number="0046760963101";
if(number.startsWith("00")) {
number=number.replaceFirst("00", "+");
}
System.out.println(number);
}
You could replace the 00 with a + like so:
String str = "0046760963101";
String newStr = "+";
for (int i = 2; i < str.length(); i++)
{
newStr += str.charAt(i);
}
Without regex:
String str = "0046760963101";
String replaced = str.charAt(2) == '0' ? str : str.substring(0, 2).replace("00", "+") + str.substring(2);
System.out.println(replaced);
will print:
+46760963101
Related
I'm writing a program where the user enters a String in the following format:
"What is the square of 10?"
I need to check that there is a number in the String
and then extract just the number.
If i use .contains("\\d+") or .contains("[0-9]+"), the program can't find a number in the String, no matter what the input is, but .matches("\\d+")will only work when there is only numbers.
What can I use as a solution for finding and extracting?
try this
str.matches(".*\\d.*");
If you want to extract the first number out of the input string, you can do-
public static String extractNumber(final String str) {
if(str == null || str.isEmpty()) return "";
StringBuilder sb = new StringBuilder();
boolean found = false;
for(char c : str.toCharArray()){
if(Character.isDigit(c)){
sb.append(c);
found = true;
} else if(found){
// If we already found a digit before and this char is not a digit, stop looping
break;
}
}
return sb.toString();
}
Examples:
For input "123abc", the method above will return 123.
For "abc1000def", 1000.
For "555abc45", 555.
For "abc", will return an empty string.
I think it is faster than regex .
public final boolean containsDigit(String s) {
boolean containsDigit = false;
if (s != null && !s.isEmpty()) {
for (char c : s.toCharArray()) {
if (containsDigit = Character.isDigit(c)) {
break;
}
}
}
return containsDigit;
}
s=s.replaceAll("[*a-zA-Z]", "") replaces all alphabets
s=s.replaceAll("[*0-9]", "") replaces all numerics
if you do above two replaces you will get all special charactered string
If you want to extract only integers from a String s=s.replaceAll("[^0-9]", "")
If you want to extract only Alphabets from a String s=s.replaceAll("[^a-zA-Z]", "")
Happy coding :)
The code below is enough for "Check if a String contains numbers in Java"
Pattern p = Pattern.compile("([0-9])");
Matcher m = p.matcher("Here is ur string");
if(m.find()){
System.out.println("Hello "+m.find());
}
I could not find a single pattern correct.
Please follow below guide for a small and sweet solution.
String regex = "(.)*(\\d)(.)*";
Pattern pattern = Pattern.compile(regex);
String msg = "What is the square of 10?";
boolean containsNumber = pattern.matcher(msg).matches();
Pattern p = Pattern.compile("(([A-Z].*[0-9])");
Matcher m = p.matcher("TEST 123");
boolean b = m.find();
System.out.println(b);
The solution I went with looks like this:
Pattern numberPat = Pattern.compile("\\d+");
Matcher matcher1 = numberPat.matcher(line);
Pattern stringPat = Pattern.compile("What is the square of", Pattern.CASE_INSENSITIVE);
Matcher matcher2 = stringPat.matcher(line);
if (matcher1.find() && matcher2.find())
{
int number = Integer.parseInt(matcher1.group());
pw.println(number + " squared = " + (number * number));
}
I'm sure it's not a perfect solution, but it suited my needs. Thank you all for the help. :)
Try the following pattern:
.matches("[a-zA-Z ]*\\d+.*")
Below code snippet will tell whether the String contains digit or not
str.matches(".*\\d.*")
or
str.matches(.*[0-9].*)
For example
String str = "abhinav123";
str.matches(".*\\d.*") or str.matches(.*[0-9].*) will return true
str = "abhinav";
str.matches(".*\\d.*") or str.matches(.*[0-9].*) will return false
As I was redirected here searching for a method to find digits in string in Kotlin language, I'll leave my findings here for other folks wanting a solution specific to Kotlin.
Finding out if a string contains digit:
val hasDigits = sampleString.any { it.isDigit() }
Finding out if a string contains only digits:
val hasOnlyDigits = sampleString.all { it.isDigit() }
Extract digits from string:
val onlyNumberString = sampleString.filter { it.isDigit() }
public String hasNums(String str) {
char[] nums = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] toChar = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
toChar[i] = str.charAt(i);
for (int j = 0; j < nums.length; j++) {
if (toChar[i] == nums[j]) { return str; }
}
}
return "None";
}
You can try this
String text = "ddd123.0114cc";
String numOnly = text.replaceAll("\\p{Alpha}","");
try {
double numVal = Double.valueOf(numOnly);
System.out.println(text +" contains numbers");
} catch (NumberFormatException e){
System.out.println(text+" not contains numbers");
}
As you don't only want to look for a number but also extract it, you should write a small function doing that for you. Go letter by letter till you spot a digit. Ah, just found the necessary code for you on stackoverflow: find integer in string. Look at the accepted answer.
.matches(".*\\d+.*") only works for numbers but not other symbols like // or * etc.
ASCII is at the start of UNICODE, so you can do something like this:
(x >= 97 && x <= 122) || (x >= 65 && x <= 90) // 97 == 'a' and 65 = 'A'
I'm sure you can figure out the other values...
I want to concatenate or append special character as colon : after an every 2 character in String.
For Example:
Original String are as follow:
String abc =AABBCCDDEEFF;
After concatenate or append colon are as follow:
String abc =AA:BB:CC:DD:EE:FF;
So my question is how we can achieve this in android.
Thanks in advance.
In Kotlin use chunked(2) to split the String every 2 chars and rejoin with joinToString(":"):
val str = "AABBCCDDEEFF"
val newstr = str.chunked(2).joinToString(":")
println(newstr)
will print
AA:BB:CC:DD:EE:FF
You can try below code, if you want to do without Math class functions.
StringBuilder stringBuilder = new StringBuilder();
for (int a =0; a < abc.length(); a++) {
stringBuilder.append(abc.charAt(a));
if (a % 2 == 1 && a < abc.length() -1)
stringBuilder.append(":");
}
Here
a % 2 == 1 ** ==> this conditional statement is used to append **":"
a < abc.length() -1 ==> this conditional statement is used not to add ":"
in last entry. Hope this makes sense. If you found any problem please let me know.
Use a StringBuilder:
StringBuilder sb = new StringBuilder(abc.length() * 3 / 2);
String delim = "";
for (int i = 0; i < abc.length(); i += 2) {
sb.append(delim);
sb.append(abc, i, Math.min(i + 2, abc.length()));
delim = ":";
}
String newAbc = sb.toString();
Here is the Kotlin way. without StringBuilder
val newString: String = abc.toCharArray().mapIndexed { index, c ->
if (index % 2 == 1 && index < abc.length - 1) {
"$c:"
} else {
c
}
}.joinToString("")
You can combine String.split and String.join (TextUtils.join(":", someList) for android) to first split the string at each second char and join it using the delimiter you want. Example:
String abc = "AABBCCDDEEFF";
String def = String.join(":", abc.split("(?<=\\G.{2})"));
System.out.println(def);
//AA:BB:CC:DD:EE:FF
Looking for a Regular Expression in Java to separate a String that represents complex numbers. A code sample would be great.
The input string will be in the form:
"a+bi"
Example: "300+400i", "4+2i", "5000+324i".
I need to retrieve 300 & 400 from the String.'
I know we can do it crudely in this way.
str.substring(0, str.indexOf('+'));
str.substring(str.indexOf('+')+1,str.indexOf("i"));
I need to retrieve 300 & 400 from the String.
What about using String.split(regex) function:
String s[] = "300-400i".split("[\\Q+-\\Ei]");
System.out.println(s[0]+" "+s[1]); //prints 300 400
Regex that matches this is: /[0-9]{1,}[+-][0-9]{1,}i/
You can use this method:
Pattern complexNumberPattern = Pattern.compile("[0-9]{1,}");
Matcher complexNumberMatcher = complexNumberPattern.matcher(myString);
and use find and group methods on complexNumberMatcher to retrieve numbers from myString
Use this one:
[0-9]{1,}
It'll return the numbers.
Hope it helps.
Regex
([-+]?\d+\.?\d*|[-+]?\d*\.?\d+)\s*\+\s*([-+]?\d+\.?\d*|[-+]?\d*\.?\d+)i
Example Regex
http://rubular.com/r/FfOAt1zk0v
Example Java
string regexPattern =
// Match any float, negative or positive, group it
#"([-+]?\d+\.?\d*|[-+]?\d*\.?\d+)" +
// ... possibly following that with whitespace
#"\s*" +
// ... followed by a plus
#"\+" +
// and possibly more whitespace:
#"\s*" +
// Match any other float, and save it
#"([-+]?\d+\.?\d*|[-+]?\d*\.?\d+)" +
// ... followed by 'i'
#"i";
Regex regex = new Regex(regexPattern);
Console.WriteLine("Regex used: " + regex);
while (true)
{
Console.WriteLine("Write a number: ");
string imgNumber = Console.ReadLine();
Match match = regex.Match(imgNumber);
double real = double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
double img = double.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);
Console.WriteLine("RealPart={0};Imaginary part={1}", real, img);
}
Try this one. As for me, it works.
public static void main(String[] args) {
String[] attempts = new String[]{"300+400i", "4i+2", "5000-324i", "555", "2i", "+400", "-i"};
for (String s : attempts) {
System.out.println("Parsing\t" + s);
printComplex(s);
}
}
static void printComplex(String in) {
String[] parts = in.split("[+-]");
int re = 0, im = 0, pos = -1;
for (String s : parts) {
if (pos != -1) {
s = in.charAt(pos) + s;
} else {
pos = 0;
if ("".equals(s)) {
continue;
}
}
pos += s.length();
if (s.lastIndexOf('i') == -1) {
if (!"+".equals(s) && !"-".equals(s)) {
re += Integer.parseInt(s);
}
} else {
s = s.replace("i", "");
if ("+".equals(s)) {
im++;
} else if ("-".equals(s)) {
im--;
} else {
im += Integer.parseInt(s);
}
}
}
System.out.println("Re:\t" + re + "\nIm:\t" + im);
}
Output:
Parsing 300+400i
Re: 300
Im: 400
Parsing 4i+2
Re: 2
Im: 4
Parsing 5000-324i
Re: 5000
Im: -324
Parsing 555
Re: 555
Im: 0
Parsing 2i
Re: 0
Im: 2
In theory you could use something like this:
Pattern complexNumberPattern = Pattern.compile("(.*)+(.*)");
Matcher complexNumberMatcher = complexNumberPattern.matcher(myString);
if (complexNumberMatcher.matches()) {
String prePlus = complexNumberMatcher.group(1);
String postPlus = complexNumberMatcher.group(2);
}
The advantage this would give you over selecting the numbers, is that it would allow you to read things like:
5b+17c as 5b and 17c
edit: just noticed you didn't want the letters, so never mind, but this would give you more control over it in case other letters appear in it.
I have a string,
String s = "test string (67)";
I want to get the no 67 which is the string between ( and ).
Can anyone please tell me how to do this?
There's probably a really neat RegExp, but I'm noob in that area, so instead...
String s = "test string (67)";
s = s.substring(s.indexOf("(") + 1);
s = s.substring(0, s.indexOf(")"));
System.out.println(s);
A very useful solution to this issue which doesn't require from you to do the indexOf is using Apache Commons libraries.
StringUtils.substringBetween(s, "(", ")");
This method will allow you even handle even if there multiple occurrences of the closing string which wont be easy by looking for indexOf closing string.
You can download this library from here:
https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4
Try it like this
String s="test string(67)";
String requiredString = s.substring(s.indexOf("(") + 1, s.indexOf(")"));
The method's signature for substring is:
s.substring(int start, int end);
By using regular expression :
String s = "test string (67)";
Pattern p = Pattern.compile("\\(.*?\\)");
Matcher m = p.matcher(s);
if(m.find())
System.out.println(m.group().subSequence(1, m.group().length()-1));
Java supports Regular Expressions, but they're kind of cumbersome if you actually want to use them to extract matches. I think the easiest way to get at the string you want in your example is to just use the Regular Expression support in the String class's replaceAll method:
String x = "test string (67)".replaceAll(".*\\(|\\).*", "");
// x is now the String "67"
This simply deletes everything up-to-and-including the first (, and the same for the ) and everything thereafter. This just leaves the stuff between the parenthesis.
However, the result of this is still a String. If you want an integer result instead then you need to do another conversion:
int n = Integer.parseInt(x);
// n is now the integer 67
In a single line, I suggest:
String input = "test string (67)";
input = input.subString(input.indexOf("(")+1, input.lastIndexOf(")"));
System.out.println(input);`
You could use apache common library's StringUtils to do this.
import org.apache.commons.lang3.StringUtils;
...
String s = "test string (67)";
s = StringUtils.substringBetween(s, "(", ")");
....
Test String test string (67) from which you need to get the String which is nested in-between two Strings.
String str = "test string (67) and (77)", open = "(", close = ")";
Listed some possible ways: Simple Generic Solution:
String subStr = str.substring(str.indexOf( open ) + 1, str.indexOf( close ));
System.out.format("String[%s] Parsed IntValue[%d]\n", subStr, Integer.parseInt( subStr ));
Apache Software Foundation commons.lang3.
StringUtils class substringBetween() function gets the String that is nested in between two Strings. Only the first match is returned.
String substringBetween = StringUtils.substringBetween(subStr, open, close);
System.out.println("Commons Lang3 : "+ substringBetween);
Replaces the given String, with the String which is nested in between two Strings. #395
Pattern with Regular-Expressions: (\()(.*?)(\)).*
The Dot Matches (Almost) Any Character
.? = .{0,1}, .* = .{0,}, .+ = .{1,}
String patternMatch = patternMatch(generateRegex(open, close), str);
System.out.println("Regular expression Value : "+ patternMatch);
Regular-Expression with the utility class RegexUtils and some functions.
Pattern.DOTALL: Matches any character, including a line terminator.
Pattern.MULTILINE: Matches entire String from the start^ till end$ of the input sequence.
public static String generateRegex(String open, String close) {
return "(" + RegexUtils.escapeQuotes(open) + ")(.*?)(" + RegexUtils.escapeQuotes(close) + ").*";
}
public static String patternMatch(String regex, CharSequence string) {
final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
final Matcher matcher = pattern .matcher(string);
String returnGroupValue = null;
if (matcher.find()) { // while() { Pattern.MULTILINE }
System.out.println("Full match: " + matcher.group(0));
System.out.format("Character Index [Start:End]«[%d:%d]\n",matcher.start(),matcher.end());
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
if( i == 2 ) returnGroupValue = matcher.group( 2 );
}
}
return returnGroupValue;
}
String s = "test string (67)";
int start = 0; // '(' position in string
int end = 0; // ')' position in string
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == '(') // Looking for '(' position in string
start = i;
else if(s.charAt(i) == ')') // Looking for ')' position in string
end = i;
}
String number = s.substring(start+1, end); // you take value between start and end
String result = s.substring(s.indexOf("(") + 1, s.indexOf(")"));
public String getStringBetweenTwoChars(String input, String startChar, String endChar) {
try {
int start = input.indexOf(startChar);
if (start != -1) {
int end = input.indexOf(endChar, start + startChar.length());
if (end != -1) {
return input.substring(start + startChar.length(), end);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return input; // return null; || return "" ;
}
Usage :
String input = "test string (67)";
String startChar = "(";
String endChar = ")";
String output = getStringBetweenTwoChars(input, startChar, endChar);
System.out.println(output);
// Output: "67"
Another way of doing using split method
public static void main(String[] args) {
String s = "test string (67)";
String[] ss;
ss= s.split("\\(");
ss = ss[1].split("\\)");
System.out.println(ss[0]);
}
Use Pattern and Matcher
public class Chk {
public static void main(String[] args) {
String s = "test string (67)";
ArrayList<String> arL = new ArrayList<String>();
ArrayList<String> inL = new ArrayList<String>();
Pattern pat = Pattern.compile("\\(\\w+\\)");
Matcher mat = pat.matcher(s);
while (mat.find()) {
arL.add(mat.group());
System.out.println(mat.group());
}
for (String sx : arL) {
Pattern p = Pattern.compile("(\\w+)");
Matcher m = p.matcher(sx);
while (m.find()) {
inL.add(m.group());
System.out.println(m.group());
}
}
System.out.println(inL);
}
}
The "generic" way of doing this is to parse the string from the start, throwing away all the characters before the first bracket, recording the characters after the first bracket, and throwing away the characters after the second bracket.
I'm sure there's a regex library or something to do it though.
The least generic way I found to do this with Regex and Pattern / Matcher classes:
String text = "test string (67)";
String START = "\\("; // A literal "(" character in regex
String END = "\\)"; // A literal ")" character in regex
// Captures the word(s) between the above two character(s)
String pattern = START + "(\w+)" + END;
Pattern pattern = Pattern.compile(pattern);
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
System.out.println(matcher.group()
.replace(START, "").replace(END, ""));
}
This may help for more complex regex problems where you want to get the text between two set of characters.
The other possible solution is to use lastIndexOf where it will look for character or String from backward.
In my scenario, I had following String and I had to extract <<UserName>>
1QAJK-WKJSH_MyApplication_Extract_<<UserName>>.arc
So, indexOf and StringUtils.substringBetween was not helpful as they start looking for character from beginning.
So, I used lastIndexOf
String str = "1QAJK-WKJSH_MyApplication_Extract_<<UserName>>.arc";
String userName = str.substring(str.lastIndexOf("_") + 1, str.lastIndexOf("."));
And, it gives me
<<UserName>>
String s = "test string (67)";
System.out.println(s.substring(s.indexOf("(")+1,s.indexOf(")")));
Something like this:
public static String innerSubString(String txt, char prefix, char suffix) {
if(txt != null && txt.length() > 1) {
int start = 0, end = 0;
char token;
for(int i = 0; i < txt.length(); i++) {
token = txt.charAt(i);
if(token == prefix)
start = i;
else if(token == suffix)
end = i;
}
if(start + 1 < end)
return txt.substring(start+1, end);
}
return null;
}
This is a simple use \D+ regex and job done.
This select all chars except digits, no need to complicate
/\D+/
it will return original string if no match regex
var iAm67 = "test string (67)".replaceFirst("test string \\((.*)\\)", "$1");
add matches to the code
String str = "test string (67)";
String regx = "test string \\((.*)\\)";
if (str.matches(regx)) {
var iAm67 = str.replaceFirst(regx, "$1");
}
---EDIT---
i use https://www.freeformatter.com/java-regex-tester.html#ad-output to test regex.
turn out it's better to add ? after * for less match. something like this:
String str = "test string (67)(69)";
String regx1 = "test string \\((.*)\\).*";
String regx2 = "test string \\((.*?)\\).*";
String ans1 = str.replaceFirst(regx1, "$1");
String ans2 = str.replaceFirst(regx2, "$1");
System.out.println("ans1:"+ans1+"\nans2:"+ans2);
// ans1:67)(69
// ans2:67
String s = "(69)";
System.out.println(s.substring(s.lastIndexOf('(')+1,s.lastIndexOf(')')));
Little extension to top (MadProgrammer) answer
public static String getTextBetween(final String wholeString, final String str1, String str2){
String s = wholeString.substring(wholeString.indexOf(str1) + str1.length());
s = s.substring(0, s.indexOf(str2));
return s;
}
I have a list of strings
0-30
31-60
61-90
91-120
365+
I want a regex which can be put into java split method to get the first no, i.e
0
31
61
91
365
Currently I am using this logic:
if(str.endsWith("+") ){
str= str.substring(0, str.length()-1);
}
String Num = str.split("-")[0];
Is there any better way ?
Thanks
String[] splitArray = subjectString.split("[+-]\\d*\\s*");
String pattern = "[+-]\\d*\\s*";
String digits = "0-30 31-60 61-90 91-120 365+";
Pattern splitter = Pattern.compile(pattern);
String[] result = splitter.split(digits );
for (String digit: result ) {
System.out.println("digits = \"" + digit + "\"");
}