Replacing specail character and it rightmost string [duplicate] - java

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to replace special character and its next string with one string
I have the following String:
"Hello $employee.$currency and $bankbalance"
My task is replacing $ and the following String with another String.
I will get more Strings like this in run time and have to scan and identify anything that starts with $ and should replace with corresponding String.
At run time string with starts with $ should replaced with single string in all it occurences

I will suggest use regex "\$[^. \n\0$]+"
Find the first and last index of the pattern.
Pattern pattern = Pattern.compile("\$[^\. \\n$]+");
Matcher matcher = pattern.matcher(string)
if (matcher.find()) {
start = matcher.start()
end = matcher.end()
text = matcher.group()
}
and replace that part of the string.

String st = "Hello $employee.$currency and $bankbalance";
String pattern = "[$]\\w+";
String res = st.replaceAll(pattern,"mystring");
System.out.println(res);
Output = Hello mystring.mystring and mystring
For Java regex tutorial

Related

Regex to find substring and wrap it in tags - Java [duplicate]

This question already has answers here:
Can I replace groups in Java regex?
(6 answers)
Closed 1 year ago.
I'm trying to write code which finds all words that are in the following format
"some text":
So alphanumeric characters which are within " symbols and which end with the : symbol. My goal once I find these is to remove the " character and wrap the entire string in tag. So after the code has run, the above text would look like this,
<strong>some text:</strong>
So I believe the regex to find such text for wrapping is the following (formatted for Java),
(\".*?\"):{1}
And by using the following code, I should be able to iterate through all the matches.
Pattern pattern = Pattern.compile("(\".*?\"):{1}");
Matcher matcher = pattern.matcher(stringToSearch);
while(matcher.find()) {
String matchedGroup = matcher.group();
matchedGroup = matchedGroup.replaceAll("\"", "");
matchedGroup = "<strong>" + matchedGroup + "</strong>";
// now what?
}
So I probably went about that all wrong.
Now that I've wrapped the word I wanted in a strong tag, how do I "put it back" where it was?
Assuming you expect your double quotes to always be balanced, you may just use String#replaceAll here for a more terse solution:
String input = "Here is \"some text\": and also \"some other text\":";
String output = input.replaceAll("\"(.*?)\":", "<strong>$1:</strong>");
System.out.println(output);
This prints:
Here is <strong>some text:</strong> and also <strong>some other text:</strong>

How to capture a regex group for below pattern [duplicate]

This question already has answers here:
Regex: match everything but a specific pattern
(6 answers)
Closed 3 years ago.
I am exploring java regex groups and I am trying to replace a string with some characters.
I have a string str = "abXYabcXYZ"; and I am trying to replace all characters except for the pattern group abc in string.
I tried to use str.replaceAll("(^abc)",""), but it did not work. I understand that (abc) will match a group.
You might find it easier to find the parts you want to keep and just build a new string. There are flaws with this issue with overlapping patterns, but it will likely be good enough for your use case. However, if your pattern really is as simple as "abc" then you may want to instead consider just counting the total number of matches.
String str = "abXYabcXYZ";
Pattern patternToKeep = Pattern.compile("abc");
MatchResult matches = patternToKeep.matcher(str).toMatchResult();
StringBuilder sb = new StringBuilder();
for (int i = 1; i < matches.groupCount(); i++) {
sb.append(matches.group(i));
}
System.out.println(sb.toString());
It is easier to keep the matching parts of the pattern and concatenate them. In the following example the matcher iterates with find() over str and match the next pattern. In the loop your "abc" pattern will be always found at group(0).
String str = "abXYabcXYZabcxss";
Pattern pattern = Pattern.compile("abc");
StringBuilder sb = new StringBuilder();
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
sb.append(matcher.group(0));
}
System.out.println(sb.toString());
For only replacing, the nearest you can get would be:
((?!abc).)*
But with the problem that only the a's of abc would not be replaced.
Regex101 example

Using or '|' in regex [duplicate]

This question already has answers here:
Difference between matches() and find() in Java Regex
(5 answers)
Closed 5 years ago.
I am stuck in a simple issue I want to check if any of the words : he, be, de is present my text.
So I created the pattern (present in the code) using '|' to symbolize OR
and then I matched against my text. But the match is giving me false result (in print statement).
I tried to do the same match in Notepad++ using Regex search and it worked there but gives FALSE( no match) in Java. C
public class Del {
public static void main(String[] args) {
String pattern="he|be|de";
String text= "he is ";
System.out.println(text.matches(pattern));
}
}
Can any one suggest what am I doing wrong.
Thanks
It's because you are trying to match against the entire string instead of the part to find. For example, this code will find that only a part of the string is conforming to the present regex:
Matcher m = Pattern.compile("he|be|de").matcher("he is ");
m.find(); //true
When you want to match an entire string and check if that string contains he|be|de use this regex .*(he|be|de).*
. means any symbol, * is previous symbol may be present zero or more times.
Example:
"he is ".matches(".*(he|be|de).*"); //true
String regExp="he|be|de";
Pattern pattern = Pattern.compile(regExp);
String text = "he is ";
Matcher matcher = pattern.matcher(text);
System.out.println(matcher.find());

java split by bracket and keep the delmiter - RegEx [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 6 years ago.
i am trying to split the string using regex with closing bracket as a delimiter and have to keep the bracket..
i/p String: (GROUP=test1)(GROUP=test2)(GROUP=test3)(GROUP=test4)
needed o/p:
(GROUP=test1)
(GROUP=test2)
(GROUP=test3)
(GROUP=test4)
I am using the java regex - "\([^)]*?\)" and it is throwing me the error..Below is the code I am using and when I try to get the group, its throwing the error..
Pattern splitDelRegex = Pattern.compile("\\([^)]*?\\)");
Matcher regexMatcher = splitDelRegex.matcher("(GROUP=test1)(GROUP=test2) (GROUP=test3)(GROUP=test4)");
List<String> matcherList = new ArrayList<String>();
while(regexMatcher.find()){
String perm = regexMatcher.group(1);
matcherList.add(perm);
}
any help is appreciated..Thanks
You simply forgot to put capturing parentheses around the entire regex. You are not capturing anything at all. Just change the regex to
Pattern splitDelRegex = Pattern.compile("(\\([^)]*?\\))");
^ ^
I tested this in Eclipse and got your desired output.
You could use
str.split(")")
That would return an array of strings which you would know are lacking the closing parentheses and so could add them back in afterwards. Thats seems much easier and less error prone to me.
You could try changing this line :
String perm = regexMatcher.group(1);
To this :
String perm = regexMatcher.group();
So you read the last found group.
I'm not sure why you need to split the string at all. You can capture each of the bracketed groups with a regex.
Try this regex (\\([a-zA-Z0-9=]*\\)). I have a capturing group () that looks for text that starts with a literal \\(, contains [a-zA-Z0-9=] zero or many times * and ends with a literal \\). This is a pretty loose regex, you could tighten up the match if the text inside the brackets will be predictable.
String input = "(GROUP=test1)(GROUP=test2)(GROUP=test3)(GROUP=test4)";
String regex = "(\\([a-zA-Z0-9=]*\\))";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while(matcher.find()) { // find the next match
System.out.println(matcher.group()); // print the match
}
Output:
(GROUP=test1)
(GROUP=test2)
(GROUP=test3)
(GROUP=test4)

String.split() not working with "[]" [duplicate]

This question already has answers here:
Why can't I split a string with the dollar sign?
(6 answers)
Closed 7 years ago.
I have a IPv6 string
String str = "demo1 26:11:d0a2:f020:0:0:0:a3:2123 demo2";
String searchString = "26:11:d0a2:f020:0:0:0:a3:2123";
When i use str.split(searchString) code returns
["demo1 ", " demo2"]
Which is fine but when i use:
String str = "demo1 [26:11:d0a2:f020:0:0:0:a3]:2123 demo2";
String searchString = "[26:11:d0a2:f020:0:0:0:a3]:2123";
and do str.split(searchString) it reutrns
[demo1 [26:11:d0a2:f020:0:0:0:a3]:2123 demo2]
Which is wrong i guess , can some one tell why I am getting this sort of output?
Since split function takes a regex as parameter, you need to escape those brackets otherwise this [26:11:d0a2:f020:0:0:0:a3] would match a single character only.
String searchString = "\\[26:11:d0a2:f020:0:0:0:a3\\]:2123";
str.split(searchString);
It is happening because split(String str) take regex pattern string as argument. And that string will be used as regex pattern to match all the delimiter with this pattern.
In your regex pattern you are providing character sets in [].
To make it work your way you will have to use this regex pattern string :
\[26:11:d0a2:f020:0:0:0:a3\]:2123
i.e. in java :
String searchString = "\\[26:11:d0a2:f020:0:0:0:a3\\]:2123";
I hope you are familiar with the string regexs. In java, the regex [abc] means match with a OR b OR c I encourage you to escape your square brackets try:
String str = "demo1 [26:11:d0a2:f020:0:0:0:a3]:2123 demo2";
String searchString = "\\[26:11:d0a2:f020:0:0:0:a3\\]:2123";
You have to use an escape sequence for some special characters. Use \\[ ... \\] in the searchString variable.

Categories