So I'm looking to get the first numbers of an IP. Let's say I have something like 255.35.54.34. I want to get the first part of numbers up until the first period. How would I do this in Java? So it'd leave me with 255.
Take a look at the String class. You can use a couple of methods to accomplish this:
the indexof(...) method will give you the offset of the "."
the substring(...) method will allow you to get a string using the above offset
Or another option is to use the split(...) method to get an array of all four IP values.
As #camickr says, you can use indexOf and substring thus:
String ipAddress = "192.168.1.9";
System.out.println(ipAddress.substring(0, ipAddress.indexOf('.')));
This will print "192"
You can use the split() method with a period as the argument. This will split the string along periods and give you a String[].
Then get the values just as you would from a normal array by using a subscript. In your case index 0 will get you the value
String ip = "255.255.255.255";
String[] splitIP = ip.split(".");
String required = splitIP[0];
You can do it in two ways :
One is that you use String.split() method, and other is to using StringTokenizer class.
Using String.split() :
String ip = "255.1.2.3";
String[] splitIP = ip.split("\\.");
String required = splitIP[0];
System.out.println(required);
Here \\ is required,oherwise it will throw an exception
Using StringTokenizer :
String ip = "255.1.2.3";
StringTokenizer tk=new StringTokenizer(ip,".");
while (tk.hasMoreTokens())
{
System.out.println(tk.nextToken());
break;
}
Hope this will help you..
Related
Need to parse a string having format like this -
"xxx.xxx.xxx.xxx ProxyHost=prod.loacl.com ProxyUser=test ProxyPas=tes#123 ProxyPort=1809".
Need to split or parse in such a manner that I get "prod.loacl.com" "test" "tes#123" "1809" in some strings and if any of parameters is not defined like ProxyPas then it should be null.
We need to ignore the IP addr xxx.xxx.xxx.xxx it will be always concatenated.
Do we have split or use some list to get this done...which is the best possible way to extract this information and why?
Note: Input string can change except ProxyHost parameter, user may not input the ProxyPass etc.
If you assume that format of the input string will not change, you can do something like this:
string inputString = "xxx.xxx.xxx.xxx ProxyHost=prod.loacl.com ProxyUser=test ProxyPas=tes#123 ProxyPort=1809";
string[] eachPart = inputString.Split(" ");
for(int i = 1; i < eachPart.Length; i++) // Skip the IP address
{
string[] partData = eachPart[i].Split("=");
string dataName = partData[0];
string dataValue = partData[1];
// do something with dataName and dataValue
}
However, if input string can change its format you should add some additional logic to this code.
Use regex with groups for this, sample:
var myString = "xxx.xxx.xxx.xxx ProxyHost=prod.loacl.com ProxyUser=test ProxyPas=tes123 ProxyPort=1809";
var regex = new Regex(#"ProxyHost=([^\s]+) ProxyUser=([^\s]+) ProxyPas=([^\s]+) ProxyPort=(\d+)");
var match = regex.Match(myString);
while(match != null && match.Success)
{
int i = 0;
foreach(var group in match.Groups)
{
Console.WriteLine($"Group {i}: Value:'{group}'");
i++;
}
match = match.NextMatch();
}
now you can match the groups to your properties.
One of the possible approaches is to do this Regular Expression:
([^=]+?)\=((\"[^"]+?\")|([^ ]+))
on the whole string. This allows variable input like this:
variable="this has spaces but still is recognized as one"
Problem is that seems like the variable content will be in either 3rd or 4th Group of such match, according to online regex testers, depends on if it has quotes or simply one string - must have more elegant way to do this, but can't come up with any now.
You can check this document to understand more about C#'s regexp groups:
Match.Groups
You will have to deal with null inputs accordingly, when you are putting the content into your C# variable.
I have a string = ab:cd:ef:gh. On this input, I want to return the string ef:gh (third colon intact).
The string apple:orange:cat:dog should return cat:dog (there's always 4 items and 3 colons).
I could have a loop that counts colons and makes a string of characters after the second colon, but I was wondering if there exists some easier way to solve it.
You can use the split() method for your string.
String example = "ab:cd:ef:gh";
String[] parts = example.split(":");
System.out.println(parts[parts.length-2] + ":" + parts[parts.length-1]);
String example = "ab:cd:ef:gh";
String[] parts = example.split(":",3); // create at most 3 Array entries
System.out.println(parts[2]);
The split function might be what you're looking for here. Use the colon, like in the documentation as your delimiter. You can then obtain the last two indexes, like in an array.
Yes, there is easier way.
First, is by using method split from String class:
String txt= "ab:cd:ef:gh";
String[] arr = example.split(":");
System.out.println(arr[arr.length-2] + " " + arr[arr.length-1]);
and the second, is to use Matcher class.
Use overloaded version of lastIndexOf(), which takes the starting index as 2nd parameter:
str.substring(a.lastIndexOf(":", a.lastIndexOf(":") - 1) + 1)
Another solution would be using a Pattern to match your input, something like [^:]+:[^:]+$. Using a pattern would probably be easier to maintain as you can easily change it to handle for example other separators, without changing the rest of the method.
Using a pattern is also likely be more efficient than String.split() as the latter is also converting its parameter to a Pattern internally, but it does more than what you actually need.
This would give something like this:
String example = "ab:cd:ef:gh";
Pattern regex = Pattern.compile("[^:]+:[^:]+$");
final Matcher matcher = regex.matcher(example);
if (matcher.find()) {
// extract the matching group, which is what we are looking for
System.out.println(matcher.group()); // prints ef:gh
} else {
// handle invalid input
System.out.println("no match");
}
Note that you would typically extract regex as a reusable constant to avoid compiling the pattern every time. Using a constant would also make the pattern easier to change without looking at the actual code.
I need to substract an specific parameter (urlReturn) from a URL like this :
http://somedomain.mx/th=6048000&campus=A&matric=L01425785&serv=GRAD&count=2&per=TEST&passwd=69786e720c0f0e&mount=1000.00&urlReturn=http://somedomain.mx:7003/SP/app/login.xhtml?id=1234&mat=2323&fh=05012014124755&store=TESO
My final string should look like this:
String urlReturn = http://somedomain.mx:7003/SP/app/login.xhtml?id=1234&mat=2323;
And the rest of the string should look like this:
String urlReturn2 = http://somedomain.mx/th=6048000&campus=A&matric=L01425785&serv=GRAD&count=2&per=TEST&passwd=69786e720c0f0e&mount=1000.00&fh=05012014124755&store=TESO
I currently have this :
String string = string.toString().split("\\&")[0];
But the urlReturn parameter should always come as the first one.
Try this (s is your original String):
urlReturn = s.substring(0, s.indexOf("&urlReturn=")).replace("&urlReturn=", "");
urlReturn2 = s.substring(s.indexOf("&urlReturn=")).replace("&urlReturn=", "");
Definitely not elegant at all, but working. I really need some sleep now so take my anser carefully :) You may alswo wanto to check if the parameters is in the String s via the contains method to avoid index out of bounds exceptions.
use string#split
url.split("\\?")[1];
I have a string like this:
String str="\"myValue\".\"Folder\".\"FolderCentury\"";
Is it possible to split the above string by . but instead of getting three resulting strings only two like:
columnArray[0]= "myValue"."Folder";
columnArray[1]= "FolderCentury";
Or do I have to use an other java method to get it done?
Try this.
String s = "myValue.Folder.FolderCentury";
String[] a = s.split(java.util.regex.Pattern.quote("."));
Hi programmer/Yannish,
First of all the split(".") will not work and this will not return any result. I think java String split method not work for . delimiter, so please try java.util.regex.Pattern.quote(".") instead of split(".")
As I posted on the original Post (here), the next code:
String input = "myValue.Folder.FolderCentury";
String regex = "(?!(.+\\.))\\.";
String[] result=input.split(regex);
System.out.println("result: "+Arrays.toString(result));
Produces the required output (an array with two values):
result: [myValue.Folder, FolderCentury]
If the problem you're trying to solve is really that specific, you could do it even without using regular expression matches at all:
int lastDot = str.lastIndexOf(".");
columnArray[0] = str.substring(0, lastDot);
columnArray[1] = str.substring(lastDot + 1);
I have one String = GETMSG_m_m_5556 from this I want to read only 5556, means I want to read all the digits after last "_". The string has not fixed length of numbers it may be like, GETMSG_m_m_9898786589 OR GETMSG_m_m_98987865. So how can I read the numbers after "_"?
Can anyone suggest me the write way.? It may be foolish question but I am stuck on this. I cant get any idea about this.
Thanks in advance.
String digits = sampleString.subString(sampleString.lastIndexOf("_"),sampleString.lenght);
Get the last index of the char '_' in your string and make a required substring to get the numbers .see string.subString()
You can use the string.split() function and take last string.
String[] separated = yourString.split("_");
// Now choose the last array value
You can try using StringTokenizer
StringTokenizer st = new StringTokenizer(String);
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (s.startsWith("_")) {
....
}}