Java - Parsing unformatted string - java

I have an unformatted string like this:
Tabs,[
{ tab1 = {
Title = tab1name
}
}
{ tab2 = {
Title = tab2name
}
}
{ tab3 = {
Title = tab3name
}
}
]
I need to parse this string and i need the title from it.
Is there is any other way to do like json parsing ?
Any help please.

Your question is a bit unclear - are you trying to parse source code or are you trying to parse the elements within the Tab[] object? If you're looking into this for a serious project, I'd recommend looking into something like cup. If it's something simpler and you merely need specific information from a collection of strings, you can use a variety of string methods. For instance -
replace()
split()
substring()
toUpperCase()
etc...
You can find more on this documentation here, I'd recommend it for a good read that might help you answer this and future questions.

Related

Unable to retrieve the value of a specific text in java

I have a long text like below:
name="sessionValidity" value="2018-09-13T16:28:28Z" type="hidden"
name="shipBeforeDate" value= "2018-09-17" name="merchantReturnData"
value= "",name="shopperLocale" value="en_GB" name="skinCode"
value="CeprdxkMuQ" name="merchantSig"
value="X70xAkOaaAeWGxNgWnTJolmy6/FFoFaBD47IzyBYWf4="
Now, I have to find all the data which are stored in the value string.
Please help.
Usually the worst thing you could do is parsing an HTML with regex. Detailed explonation here.
For the purpose of parsing the data and manipulate it the right way you should considering using an advanced markup parser like jaxb, jsoup, or any other.
Of course it is a case specific decision and in your case maybe this one could do the work...
private static List<String> extractValuesAsUselessList(String theString) {
List<String> attributes = new ArrayList<>();
if (theString != null && !theString.equals("")) {
Matcher matcher = Pattern.compile("\\s([\\w+|-|:]+)=\"(.*?)\"").matcher(theString);
while (matcher.find()) {
if ("value".equals(matcher.group(1))) {
attributes.add(matcher.group(2));
}
}
}
return attributes;
}

Assign from array to list of strings in Java

Is there a way to get rid of buf?
public Option(String opt) {
String[] buf;
buf = opt.split("=");
key = buf[0];
value = buf[1];
}
I thought of something like { key, val } = opt.split("="); as it would be possible in Perl, IIRC.
There is java.util.Scanner, which gives back one token at a time. But it's a lot harder to use than split, and in my experience not worth the trouble for problems simple enough to handle w/ split.

One line check if String contains bannedSubstrings

I have a String title and a List<String> bannedSubstrings. Now I want to perform a one line check if title is free of those bannedSubstrings.
My approach:
if(bannedSubstrings.stream().filter(bannedSubstring -> title.contains(bannedSubstring)).isEmpty()){
...
}
Unfortunately, there is no isEmpty() method for streams. So how would you solve the problem? Is there a one line solution?
Sounds like you want to read up on anyMatch:
if (bannedSubstrings.stream().anyMatch(title::contains)) {
// bad words!
}
Inversely, there's also noneMatch:
if (bannedSubstrings.stream().noneMatch(title::contains)) {
// no bad words :D
}
This isn't very efficient if title is a long string (but titles usually aren't supposed to be long, I suppose).
If you want an efficient solution and you have many bannedSubstrings, I guess, it would be faster to join them into single regexp like this:
Pattern badWords = Pattern.compile(bannedSubstrings.stream().map(Pattern::quote)
.collect(Collectors.joining("|")));
Then use it like this:
if (badWords.matcher(title).find()) {
...
}
This should build a prefix tree from your substrings, so scanning will be significantly faster. If performance is not the concern in your case, use other answers.
I suppose you are looking for something like this:
if(bannedSubstrings.stream().anyMatch(title::contains)){
}
The answer you've selected is pretty good, but for real performance you'd probably be better off pre-compiling the list of bad words into a regex.
public class BannedWordChecker {
public final Pattern bannedWords;
public BannedWordChecker(Collection<String> bannedWords) {
this.bannedWords =
Pattern.compile(
bannedWords.stream()
.map(Pattern::quote)
.collect(Collectors.joining("|")));
}
public boolean containsBannedWords(String string) {
return bannedWords.matcher(string).find();
}
}

Is there any easy way within Java to prefix one string onto multiple other strings?

Does anybody know if there is any easy way within Java to prefix one string onto multiple other strings?
For example, if I have the following snippet of Java code ;
String includeDir = "/usr/local/boost-1.52.0/include";
ArrayList<String> filenamesRelative = new ArrayList<String>(),
filenamesAbsolute = new ArrayList<String>();
filenamesRelative.add("/boost/aligned_storage.hpp");
filenamesRelative.add("/boost/any.hpp");
I would like to be able to prefix the value of the variable 'includeDir', i.e. "/usr/local/boost-1.52.0/include", onto the front of each value in the ArrayList filenamesRelative.
Ideally, I would like to be able to do something like the following ;
filenameAbsolute = filenamesRelative.prefixAll(includeDir);
I don't necessarily have to use ArrayLists in the solution; I have just used them above for illustrative purposes.
From memory, you can do something like this rather easily in C++ using the STL, however my current working knowledge of Java isn't all that good unfortunately :(
Thanks in advance for any assistance.
I dont know of a method in the API. but its so simple just create your own. Something like:
List<String> filenameAbsolute = new ArrayList<String>();
for ( String file: filenamesRelative ) {
filenameAbsolute.add(prefix + file);
}
Do it like this:
ArrayList<String> prefixAll(ArrayList<String> filenamesRelative)
{
ArrayList<String> filenamesAbsolute = new ArrayList<String>();
String includeDir = "/usr/local/boost-1.52.0/include";
for ( String file: filenamesRelative ) {
filenameAbsolute.add(includeDir + file);
}//for
return filenameAbsolute;
}//prefixAll()

How do I call this object to return all strings it finds?

I have the following code that defines a getParts method to find a given Part Name and Part Number in the system. Note that this code comes from our system's API, so if no one can help I'll just delete this question. I figured someone could potentially see a solution or help me along the way.
<%! private QueryResult getParts( String name, String number )
throws WTException, WTPropertyVetoException {
Class cname = wt.part.WTPart.class;
QuerySpec qs = new QuerySpec(cname);
QueryResult qr = null;
qs.appendWhere
(new SearchCondition(cname,
"master>name",
SearchCondition.EQUAL,
name,
false));
qs.appendAnd();
qs.appendWhere
(new SearchCondition(cname,
"master>number",
SearchCondition.EQUAL,
number,
false));
qr = PersistenceHelper.manager.find(qs);
System.out.println("...found: " + qr.size());
return qr;
}
%>
But I would like to allow the user more flexibility in finding these parts. So I set up conditional statements to check for a radio button. This allows them to search by part name and part number, find all, or search using a wildcard. However, I'm having trouble implementing the two latter options.
To attempt to accomplish the above, I have written the below code:
<%
String partName = request.getParameter("nameInput");
String partNumber = request.getParameter("numberInput");
String searchMethod = request.getParameter("selection");
//out.print(searchMethod);
QueryResult myResult = new QueryResult();
if(searchMethod.equals("search"))
myResult = getParts(partName, partNumber);
else if(searchMethod.equals("all"))
{
//Should I write a new function and do this?
//myResult = getAllParts();
//or is there a way I could use a for each loop to accomplish this?
}
//else if(searchMethod.equals("wildcard"))
//get parts matching %wildcard%
while(myResult.hasMoreElements())
{
out.print(myResult.nextElement().toString());
}
%>
Basically, it accepts user input and checks what type of search they would like to perform. Is there an easy way to pass all the values into the myResult object? And likewise for the wildcard search? Like I said before, it may be futile trying to help without access to the API, but hopefully it isn't.
Thanks!
You can (and should) reuse the function, but in order to do so, you will need a part name and number (as those are its input parameters). So for the multi-result options you will need to get a list/collection of part names+numbers and feed them individually to the function, then collect the result in the format that is most appropriate for your needs

Categories

Resources