How to get a token from string with multiple combination - java

I have a string with multiple combinations like below.
msqlora -sn $(PWF_pdmm8107)
msqlora -n $(PWF_pdmm8107)
msqlora $(PWF_pdmm8107)
the string is single. but at runtime, it may be formed any one of the above situation.
I want to retrieve $(PWF_pdmm8107) token from a string.
What I have done till now.
while ( st.hasMoreTokens() )
{
if ( st.nextToken().equals( "-sn" ) )
{
pwf = st.nextToken();
}
}
please suggest a way so I can retrieve $(PWF_pdmm8107) from above string combination.
Thanks

One way you could do this is to split() the string into an array using a space as a delimiter, and select the last element
String input = "msqlora -sn $(PWF_pdmm8107)";
String[] tmp = input.split(" ");
String output = tmp[tmp.length - 1];

Consider the answer if regex is allowed..
"(\\$\\(.*\\))"
String str = "msqlora -sn $(PWF_pdmm8107)\n" +
" msqlora -n $(PWF_pdmm8107)\n" +
" msqlora $(PWF_pdmm8107)";
Pattern compile = Pattern.compile("(\\$\\(.*\\))");
Matcher match = compile.matcher(str);
while( match.find())
{
System.out.println(match.group());
}
Output:-
$(PWF_pdmm8107)
$(PWF_pdmm8107)
$(PWF_pdmm8107)

Related

Parsing comma separated string with prefix

I am getting comma sepeated string in below format:
String codeList1 = "abc,pqr,100101,P101001,R108972";
or
String codeList2 = "mno, 100101,108972";
Expected Result : Check if code is numeric after removing first alphabet. If yes, remove prefix and return. If no, still return the code.
codeList1 = "abc,pqr,100101,101001,108972";
or
codeList2 = "mno, 100101,108972";
As you can see, I can get codes (P101001 or 101001) and (R108972 ,108972) format. There is will be only one prefix only.
If I am getting(P101001), I want to remove 'P' prefix and return number 101001.
If I am getting 101001, do nothing.
Below is the working code. But is there any easier or more efficient way of achieving this. Please help
for (String code : codeList.split(",")) {
if(StringUtils.isNumeric(code)) {
codes.add(code);
} else if(StringUtils.isNumeric(code.substring(1))) {
codes.add(Integer.toString(Integer.parseInt(code.substring(1))));
} else {
codes.add(code);
}
}
If you want to remove prefixes from the numbers you can easilly use :
String[] codes = {"abc,pqr,100101,P101001,R108972", "mno, 100101,108972"};
for (String code : codes){
System.out.println(
code.replaceAll("\\b[A-Z](\\d+)\\b", "$1")
);
}
Outputs
abc,pqr,100101,101001,108972
mno, 100101,108972
If you are using Java 8+, and want to extract only the numbers, you can just use :
String codeList1 = "abc,pqr,100101,P101001,R108972";
List<Integer> results = Arrays.stream(codeList1.split("\\D")) //split with non degits
.filter(c -> !c.isEmpty()) //get only non empty results
.map(Integer::valueOf) //convert string to Integer
.collect(Collectors.toList()); //collect to results to list
Outputs
100101
101001
108972
You can use regex to do it
String str = "abc,pqr,100101,P101001,R108972";
String regex = ",?[a-zA-Z]{0,}(\\d+)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
System.out.println(matcher.group(1));
}
Output
100101
101001
108972
Updated:
For your comment(I want to add add the codes. If single alphabet prefix found , remove it and add remaining ),you can use below code:
String str = "abc,pqr,100101,P101001,R108972";
String regex = "(?=,?)[a-zA-Z]{0,}(?=\\d+)|\\s";// \\s is used to remove space
String[] strs = str.replaceAll(regex,"").split(",");
Output:
abc
pqr
100101
101001
108972
How about this:
String codeList1 = "abc,pqr,100101,P101001,R108972";
String[] codes = codeList1.split(",");
for (String code : codes) {
if (code.matches("[A-Z]?\\d{6}")) {
String codeF = code.replaceAll("[A-Z]+", "");
System.out.println(codeF);
}
}
100101
101001
108972
Demo

Check if id in string and get value if so

I am trying to get a regex to match, then get the value with it. For example, I want to check for 1234 as an id and if present, get the status (which is 0 in this case). Basically its id:status. Here is what I am trying:
String topicStatus = "1234:0,567:1,89:2";
String someId = "1234";
String regex = "\\b"+someId+":[0-2]\\b";
if (topicStatus.matches(regex)) {
//How to get status?
}
Not only do I not know how to get the status without splitting and looping through, I don't know why it doesn't match the regex.
Any help would be appreciated. Thanks.
Use the Pattern class
String topicStatus = "1234:0,567:1,89:2";
String someId = "1234";
String regex = "\\b"+someId+":[0-2]\\b";
Pattern MY_PATTERN = Pattern.compile(regex);
Matcher m = MY_PATTERN.matcher(topicStatus);
while (m.find()) {
String s = m.group(1);
System.out.println(s);
}
The key here is to surround the position you want [0-2] in parenthesis which means it will be saved as the first group. You then access it through group(1)
I made some assumptions that your pairs we're always comma separate and then delimited by a colon. Using that I just used split.
String[] idsToCheck = topicStatus.split(",");
for(String idPair : idsToCheck)
{
String[] idPairArray = idPair.split(":");
if(idPairArray[0].equals(someId))
{
System.out.println("id : " + idPairArray[0]);
System.out.println("status: " + idPairArray[1]);
}
}

Why is Java placing the string before the word and not after?

from the String value want to getting word before and after the <in>
String ref = "application<in>rid and test<in>efd";
int result = ref.indexOf("<in>");
int result1 = ref.lastIndexOf("<in>");
String firstWord = ref.substring(0, result);
String[] wor = ref.split("<in>");
for (int i = 0; i < wor.length; i++) {
System.out.println(wor[i]);
}
}
my Expected Output
String[] output ={application,rid,test,efd}
i tried with 2 Option first one IndexOf but if the String have more than two <in>i 'm not getting my expected output
Second One splitits also not getting with my expected Output
please suggest best option to getting the word(before and after <in>)
You could use an expression like so: \b([^ ]+?)<in>([^ ]+?)\b (example here). This should match the string prior and after the <in> tag and place them in two groups.
Thus, given this:
String ref = "application<in>rid and test<in>efd";
Pattern p = Pattern.compile("\\b([^ ]+?)<in>([^ ]+?)\\b");
Matcher m = p.matcher(ref);
while(m.find())
System.out.println("Prior: " + m.group(1) + " After: " + m.group(2));
Yields:
Prior: application After: rid
Prior: test After: efd
Alternatively using split:
String[] phrases = ref.split("\\s+");
for(String s : phrases)
if(s.contains("<in>"))
{
String[] split = s.split("<in>");
for(String t : split)
System.out.println(t);
}
Yields:
application
rid
test
efd
Regex is your friend :)
public static void main(String args[]) throws Exception {
String ref = "application<in>rid and test<in>efd";
Pattern p = Pattern.compile("\\w+(?=<in>)|(?<=<in>)\\w+");
Matcher m = p.matcher(ref);
while (m.find()) {
System.out.println(m.group());
}
}
O/P :
application
rid
test
efd
No doubt matching what you need using Pattern/Matcher API is simpler for tis problem.
However if you're looking for a short and quick String#split solution then you can consider:
String ref = "application<in>rid and test<in>efd";
String[] toks = ref.split("<in>|\\s+.*?(?=\\b\\w+<in>)");
Output:
application
rid
test
efd
RegEx Demo
This regex splits on <in> or a pattern that matches a space followed by 0 more chars followed by a word and <in>.
You can also try the below code, it is quite simple
class StringReplace1
{
public static void main(String args[])
{
String ref = "application<in>rid and test<in>efd";
System.out.println((ref.replaceAll("<in>", " ")).replaceAll(" and "," "));
}
}

Get certain substring from String java

I can have this string as below :
String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";
or
String s = "chapterId=c_1&sectionId=s_24666";
I need to get the number ("24666" in the examples).
String res = s.substring(s.lastIndexOf("s_")+ 2) this returns me the number + chars till the end of the string(the second example is ok). But I need to stop after the number ends. How can I do that.? Thanks
You can use regExp
String s = "chapterId=c_1&sectionId=s_24666";
//OR
//String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";
s=s.replaceAll(".*?s_(\\d+).*","$1");
System.out.println(s);
OUTPUT:
24666
Where,
.*?s_ means anything before s_ (s_ inclusive)
(\\d+) means one or more digits () used for group
$1 means group 1 which is digits after s_
Note:Assumed that your every string follows specific format which includes s_ and number after s_.
You can split the string by the character & to get the parameters, and split each parameter with the = to get the parameter name and parameter value. And now look for the parameter name "sectionId", and cut the first 2 characters of its value to get the number, and you can use Integer.parseInt() if you need it as an int.
Note that this solution is flexible enough to process all parameters, not just the one you're currently interested in:
String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";
String[] params = s.split("&");
for (String param : params) {
String[] nameValue = param.split("=");
if ("sectionId".equals(nameValue[0])) {
int number = Integer.parseInt(nameValue[1].substring(2));
System.out.println(number); // Prints 24666
// If you don't care about other parameters, this will skip the rest:
break;
}
}
Note:
You might want to put Integer.parseInt() into a try-catch block in case an invalid number would be passed from the client:
try {
int number = Integer.parseInt(nameValue[1].substring(2));
} catch (Exception e) {
// Invalid parameter value, not the expected format!
}
Try this:
I use a check in the substring() method - if there is no "&isHL" in the string (meaning its type 2 you showed us), it will just read until the string ends. otherwise, it will cut the string before the "&isHL". Hope this helps.
Code:
String s = "chapterId=c_1&sectionId=s_**24666**";
int endIndex = s.indexOf("&isHL");
String answer = s.substring(s.lastIndexOf("s_") + 2, endIndex == -1 ? s.length() : endIndex);
Try following:
String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";
String tok[]=s.split("&");
for(String test:tok){
if(test.contains("s_")){
String next[]=test.split("s_");
System.out.println(next[1]);
}
}
Output :
24666
Alternatively you can simply remove all other words if they are not required as below
String s="chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";
s=s.replaceAll(".*s_(\\d+).*","$1");
System.out.println(s);
Output :
24666
The dig over here is splitting your string using a Regular Expression to further divide the string into parts and get what is required. For more on Regular Expressions visit this link.
You could sue this regex : (?<=sectionId=s_)(\\d+) This uses positive look-behind.
demo here
Following code will work even if there is multiple occurrence of integer in given string
String inputString = "chapterId=c_a&sectionId=s_24666&isHL=1&cssFileName=haynes_45";
String[] inputParams = inputString.split("&");
for (String param : inputParams)
{
String[] nameValue = param.split("=");
try {
int number = Integer.parseInt(getStringInt(nameValue[1]));
System.out.println(number);
}
catch(IllegalStateException illegalStateException){
}
}
private String getStringInt(String inputString)
{
Pattern onlyInt = Pattern.compile("\\d+");
Matcher matcher = onlyInt.matcher(inputString);
matcher.find();
String inputInt = matcher.group();
return inputInt;
}
OUTPUT
2466
1
45
Use split method as
String []result1 = s.split("&");
String result2 = tempResult[1];
String []result3 = result2.split("s_");
Now to get your desire number you just need to do
String finalResult = result3[1];
INPUT :
String s = "chapterId=c_1&sectionId=s_24666&isHL=1&cssFileName=haynes";
OUPUT :
24666

Extract given substring from a paragraph

I want to perform the following functionality :
From a given paragraph extract the given String, like
String str= "Hello this is paragraph , Ali#yahoo.com . i am entering random email here as this one AHmar#gmail.com " ;
What I have to do is to parse the whole paragraph, read the Email address, and print their server names , i have tried it using for loop with substring method , did use indexOf , but might be my logic is not that good to get it , can someone help me with it please?
You need to use Regular Expression for this case.
Try the below Regex: -
String str= "Hello this is paragraph , Ali#yahoo.com . i am " +
"entering random email here as this one AHmar#gmail.com " ;
Pattern pattern = Pattern.compile("#(\\S+)\\.\\w+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
OUTPUT: -
yahoo
gmail
UPDATE: -
Here's the code with substring and indexOf: -
String str= "Hello this is paragraph , Ali#yahoo.com . i am " +
"entering random email here as this one AHmar#gmail.com " ;
while (str.contains("#") && str.contains(".")) {
int index1 = str.lastIndexOf("#"); // Get last index of `#`
int index2 = str.indexOf(".", index1); // Get index of first `.` after #
// Substring from index of # to index of .
String serverName = str.substring(index1 + 1, index2);
System.out.println(serverName);
// Replace string by removing till the last #,
// so as not to consider it next time
str = str.substring(0, index1);
}
You need to use a regular expression to extract the email. Start off with this test harness code. Next, construct your regular expression and you should be able to extract the email address.
Try this:-
String e= "Hello this is paragraph , Ali#yahoo.com . i am entering random email here as this one AHmar#gmail.comm";
e= e.trim();
String[] parts = e.split("\\s+");
for (String e: parts)
{
if(e.indexOf('#') != -1)
{
String temp = e.substring(e.indexOf("#") + 1);
String serverName = temp.substring(0, temp.indexOf("."));
System.out.println(serverName); }}

Categories

Resources