i have a string:
String value = "(name) Says: hello (/name)";
where "name" could also be "lastName", "address" "postalCode" or many many other things.
i split the string on the "("
i want to also split on the ")" ... however, some strings will only contain the following:
String value = "(name Says: hello (/name)";
my problem is that the string content could also contain ")" and "(" so how would i parse this then? For instance:
String value = "(name Says: can you solve for y = (x-b)? (/name)";
the string could also be as follows:
String value = "(name)Says: can you solve for y = (x-b)? (/name)";
OR
String value = "(name) Says: can you solve for y = (x-b)?(/name)";
OR
String value = "(name)Says: can you solve for y = (x-b)?(/name)";
i was initially thinking that i could do a count of how many ")" there are in a string. However, if there are more than 2, i'm not sure what i should do? The reason why i would need to know how many ")" there are in a string is because i want to isolate "name"
any ideas? (i don't want to use any libraries, just want to come up with the logic )...
The question wasn't very clear to me. However,as far as I could understand,I guess that you want to capture the name and also the sentence that follows it,both seperately.Please correct me if I am wrong.
Here's the solution:
1.Parse your String until the first space after "(" .
2.Store it in a temp String. Its length is given by temp.length().
3.So check if temp.charAt(temp.length()-1)==')'.
4.If yes then name would be in the substring temp.substring(1,temp.length()-2).
5.Otherwise it would be in the substring temp.substring(1,temp.length()-1).
6.Now the value after name can be stored in another String until you find "(/".
Hope it helps.
Extract all characters after the first space and before the last space.
below code will return name in both of your condition:
String s = "(name Says: can you solve for y = (x-b)? (/name)";
int firstIndex = s.indexOf("(");
int secondIndex = s.indexOf(":");
int thirdIndex = 0;
String name = "";
if(s.substring(firstIndex, secondIndex).contains(")")) {
thirdIndex = s.indexOf(")");
} else {
thirdIndex = s.indexOf(" ");
}
System.out.println("(name) or (name : "+s.substring(firstIndex+1, thirdIndex));
String temp = s.substring(thirdIndex+1, s.length());
System.out.println(temp.substring(0, temp.indexOf("(/")));
System.out.println("(/name) : "+ temp.substring(temp.indexOf("(/")+2, temp.lastIndexOf(")")));
First parse last symbols while you will not find "(/string)"
Then get all that you have between "(/" and ")" except spaces at the edges.
And try to find in the beginning of the line kind of this construction "(" + name.trim() + ")" with or without ")"
Besides java.util.regex.* must be your best friend in this situation.
Related
My String input is String Number = "546+90".
I want to give output like this "546 + 90".how can i do it in java? Right now I am trying:
Number.replaceAll("[0-9]"," ");
But it doesn't seem to be working. Does anyone have any suggestions?
Strings are immutable so you need to get the string resultant of the replace method:
public static void main(String[] args) {
String number="546+90";
number = number.replaceAll("\\+" , " + ");
System.out.println(number);
}
First, Number is a built-in class in the java.lang package, so you should never use that name.
Second, variables should be written in lower-case, so it should be number.
Third, Strings are immutable, so the need to get the return value from replaceAll().
If you want this string: "String Number=546+90"
to become this string: "546 + 90"
then you need to strip anything before = and add spaces around the +.
This can be done by chaining replace calls:
String number = "String Number=546+90";
number = number.replaceFirst(".*=", "")
.replaceAll("\\+", " + ");
System.out.println(number);
If you want other operators too, use a character class. You have to capture the character to retain it in the replacement string, and you must put - first or last (or escape it).
number = number.replaceFirst(".*=", "")
.replaceAll("([-+*/%])", " $1 ");
Adding an escape characters will solve your problem
String Number = "\"" + "546+90" + "\"";
I'm fairly certain this is asked & answered, but I cant find an (that) answer, so I'll ask:
I want to use javas regex to find and replace. There is no markup involved (no, "${ImMarkup!} in the source string) and the value I wish to replace is contextualized (as in, I cant write a simple replace A with B).
Examples make everything easier, here's some sample code. This is the source string:
! locator's position P1(p1x,p1y),P2(p2x,p2y)
R,1,0.001,0.001,0.001,0.001, , ,
RMORE, , , ,
RMORE
RMORE, ,
ET,MPTEMP,,,,EX, x1=38000
x2 = 2345
MPTEMP,,,,,,,,
MPTEMP,1,0
MPDATA,EX,1,,38000*6894.75
my regex is
+(?<variableName>\w+) *= *-?(?<variableValue>\d+\.?\d*)
(note the space before the first plus)
I'm looking to replace that "x1=38000" with something like "x1=100", and the "x2 = 2345" with "x2 = 200"
With the output
...
RMORE, ,
ET,MPTEMP,,,,EX, x1=100
x2 = 200
MPTEMP,,,,,,,,
...
I've created a gist containing some semi-runnable code here (it uses some stuff from our commons code base, but its followable: https://gist.github.com/Groostav/acf5b584078813e7cbe6)
The code I've got is roughly
String regex = "+(?<variableName>\\w+) *= *-?(?<variableValue>\\d+\\.?\\d*)"
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(sourceText);
while(matcher.find()){
String variableName = matcher.group("variableName");
String existingValue = matcher.group("variableValue");
int newValue;
switch(variableName){
case "x1": newValue = 100; break;
case "x2": newValue = 200; break;
default: throw new IllegalStateException();
}
matcher.appendReplacement(output, "" + newValue);
}
matcher.appendTail(output);
The regex itself works: it captures the values I need, and I can access them through matcher.group("variableName") and matcher.group("variableValue"), the issue I'm having is writing a new value back to 'variableValue', with the java regex API.
In the above example, matcher.group("variableValue") doesnt persist any state, so I cant seem to specify to the appendReplacement() method that I dont want to replace the whole line, but rather simply the second capture group.
Worth metnioning, x1 and x2 are not hard-fast runtime names, so I cant simply cheese it and write separate find and replace strings for x1 and x2. I need the runtime \w+ to find the variable name.
So I can run another regex against the result of the first, this time only capturing the value, but thats not pretty, and it would require me to probably fudge index values around with our StringBuilder/Buffer, rather than that nice index-free call to matcher.appendTail.
PS: the langauge you see above is called the "ANSYS parametric design language (APDL)", and I cant find a grammar for the thing. If any of you guys know where one is, I'd hugely appreciate it.
thanks for reading.
You can use this regex:
(\w+\s*)=(\s*\d+)
Working demo
Check the substitution section. You can use the same approach to replace the content you want as I did using capturing group index.
My Hacky solution that seems to work is to manually traverse our parse tree, down the rhs, and replace the new value. This is annoying since it requires me to refactor my regex and do that manual work, but it does do the job, and I believe its reliable:
// semi-formally, APDL seems to define:
// AssignmentExpression -> QualifiedIdentifier = Expression
// QualifiedIdentifier -> SPACE+ Identifier SPACE*
// Expression -> SPACE* Value //Value is captured as "value"
// Identifier -> [A-Za-z0-9]* //Identifier is captured as "identifier"
// Value -> [0-9]* (DOT [0-9]*)?
private static final String rValue = "\\d+(\\.\\d*)?";
private static final String rIdentifier = "(?<identifier>\\w+)";
private static final String rQualifiedIdentifier = " +" + rIdentifier + " *";
private static final String rExpression = " *-?(?<value>" + rValue + ")";
private static final String rAssignmentExpression = rQualifiedIdentifier + "=" + rExpression;
#Test
public void when_scanning_using_our_regex(){
Pattern assignmentPattern = Pattern.compile(rAssignmentExpression);
Pattern rhsPattern = Pattern.compile("=" + rExpression);
Pattern valuePattern = Pattern.compile(rValue);
Matcher assignmentMatcher = assignmentPattern.matcher(sourceText);
StringBuffer output = new StringBuffer();
int newValue = 20;
while(assignmentMatcher.find()){
String assignment = assignmentMatcher.group();
Matcher rhsMatcher = rhsPattern.matcher(assignment);
assert rhsMatcher.find() : "couldn't find an RHS in an the assignment: '" + assignment + "'?";
String oldRhs = rhsMatcher.group();
Matcher valueMatcher = valuePattern.matcher(oldRhs);
assert valueMatcher.find() : "couldn't find a value in an RHS: '" + oldRhs + "'?";
String oldValue = valueMatcher.group();
String newRhs = oldRhs.replace(oldValue, "" + newValue);
String newAssignment = assignment.replace(oldRhs, newRhs);
assignmentMatcher.appendReplacement(output, "" + newAssignment);
}
assignmentMatcher.appendTail(output);
System.out.println(output.toString());
}
Hi I have a question about how to get only part of given string :
String = "1. Name:Tom\tNumber:123";
in this case I would like to get only part with name ( "Tom" )
Is there is any solution to do it?
Thank's for help
This is a simple way assuming the format won't change.
int start = yourString.indexOf(':') + 1; //get character after this
int end = yourString.indexOf('\t');
String result = yourString.substring(start,end);
You can also write your own regex to match this.
If that format is how it always shows up this would work:
String str = "1. Name:Tom\tNumber:123";
String tom = str.substring(str.indexOf(':')+1, str.indexOf('\t'));
Using the first occurrence of : and the \t allows you to parse out the name. In the case of your :, you want to begin your string 1 character ahead.
Result:
Tom
What you need, you will easyly find at the String documentation.
From a server, I get strings of the following form:
String x = "fixedWord1:var1 data[[fixedWord2:var2 fixedWord3:var3 data[[fixedWord4] [fixedWord5=var5 fixedWord6=var6 fixedWord7=var7]]] , [fixedWord2:var2 fixedWord3:var3 data[[fixedWord4][fixedWord5=var5 fixedWord6=var6 fixedWord7=var7]]]] fixedWord8:fixedWord8";
(only spaces divide groups of word-var pairs)
Later, I want to store them in a Hashmap, like myHashMap.put(fixedWord1, var1); and so on.
Problem:
Inside the first "data[......]"-tag, the number of other "data[..........]"-tags is variable, and I don't know the length of the string in advance.
I don't know how to process such Strings without resorting to String.split(), which is discouraged by our assignment task givers (university).
I have searched the internet and couldn't find appropriate websites explaining such things.
It would be of great help, if experienced people could give me some links to websites or something like a "diagrammatic plan" so that I could code something.
EDIT:
got mistake in String (off-topic-begin "please don't lynch" off-topic-end), the right string is (changed fixedWord7=var7 ---to---> fixedWord7=[var7]):
String x = "fixedWord1:var1 data[[fixedWord2:var2 fixedWord3:var3 data[[fixedWord4] [fixedWord5=var5 fixedWord6=var6 fixedWord7=[var7]]]] , [fixedWord2:var2 fixedWord3:var3 data[[fixedWord4][fixedWord5=var5 fixedWord6=var6 fixedWord7=[var7]]]]] fixedWord8:fixedWord8";
I assume your string follows a same pattern, which has "data" and "[", "]" in it. And the variable name/value will not include these strings
remove string "data[", "[", "]", and "," from the original string
replaceAll("data[", "")
replaceAll("[", "")
etc
separate the string by space: " " by using StringTokenizer or loop through the String char by char.
then you will get array of strings like
fixedWorld1:var1
fixedWorld2:var2
......
fixedWorld4
fixedWorld5=var5
......
then again separate the sub strings by ":" or "=". and put the name/value into the Map
Problem is not absolutely clear but may be something like this will work for you:
Pattern p = Pattern.compile("\\b(\\w+)[:=]\\[?(\\w+)");
Matcher m = p.matcher( x );
while( m.find() ) {
System.out.println( "matched: " + m.group(1) + " - " + m.group(2) );
hashMap.put ( m.group(1), m.group(2) );
}
I have a string like delivery:("D1_0"), how do i get the value inside the quotes alone from it. i.e D1_0 alone from it.
You could use regualr expresion like \"(.*?)\" to find that group, or even better, iterate over your String looking for quote marks " and reading characters inside of them until you find another quote mark. Something similar to this.
Try this
int i = stringvariable.indexOf("(");
int j = stringvariable.indexOf(")");
String output = stringvariable.substring(i+2, j-2);
You will get the required value in output variable.
If your string is constant, in that the beginning of the string will not change, you could use the slice function
In Javascript:
var text='delivery:("D1_0")';
alert(text.slice(11, 15)); //returns "D1_0"
In Java:
String text = "delivery:(\"D1_0\")";
String extract = text.substring(11, 15);
Use:
String str = "delivery:(\"D1_0\")";
String arr[] = str.split("[:\"()]"); //you will get arr[delivery, , , D1_0], choose arr[3]
System.out.println(arr[3]);
"If your String is always in this format you can use
String theString = "delivery:(\"D1_0\")";
String array[] = theString.split("\"");
String result = array[1]; // now result string is D1_0
// Note: array[0] contains the first part(i.e "delivery:(" )
// and array[2] contains the second (i.e ")" )