Increment digit inside string - java

Hi i want to increment the integer values in between the string.
for example the initial string is -- m1p1b1.
The below code is working correctly, But it has one problem.
When the string is m10p10b10 it gives the result m21p21b21 not m11p11b11.
Also the integer length between the string dynamic, So i cant do any static code.
Pattern digitPattern = Pattern.compile("(\\d)");
Matcher matcher = digitPattern.matcher("m1p1b1");
StringBuffer result = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(result, String.valueOf(Integer.parseInt(matcher.group(1)) + 1));
}
matcher.appendTail(result);
System.out.println(result.toString());

Change \\d to \\d+ to match one or more digits:
Pattern digitPattern = Pattern.compile("\\d+");
Matcher matcher = digitPattern.matcher("m10p10b10");
StringBuffer result = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(result, String.valueOf(Integer.parseInt(matcher.group(0)) + 1));
}
matcher.appendTail(result);
System.out.println(result.toString()); // => m11p11b11
See the IDEONE demo
Note you do not have to capture the whole pattern with (...), you can access the value using matcher.group(0).

Related

Java Regex compress String

I have random String for example "aaaaaaBccccCCCCd" I need make regex which searches the text for groups to get effect "a6B1c4C4d1". My regex looks like that "(\\D+)\\D*\\1" but he lost single letters, so in this sample B and d.
Maybe someone would have an idea?
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Compress {
public static void main(String[] args) {
String text = "aaaaaaBccccCCCCd";
String regex = "(\\D+)\\D*\\1"; // or (.+).*\\1
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
String result = new String();
while (matcher.find()) {
String letter = matcher.group().substring(0, 1);
String numberOfLetter = String.valueOf(matcher.group().length());
result = result + letter + numberOfLetter;
}
System.out.println(result);
}
}
Thank you.
Use the following approach based on Matcher#appendReplacement:
String text = "aaaaaaBccccCCCCd"; //a6B1c4C4d1
String regex = "(.)(\\1*)";
String pattern = "test";
Pattern r = Pattern.compile(regex);
Matcher m = r.matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1) + (m.group(2).length()+1));
}
m.appendTail(sb);
System.out.println(sb);
See the Java demo
The (.)(\1*) will capture any char into Group 1 and then will capture into Group 2 zero or more repetitions of the same content. In the "callback", Group 1 is concatenated with the length of Group 2 incremented to account for the Group 1 length.

Replace group 1 of Java regex with out replacing the entire regex

I have a regex pattern that will have only one group. I need to find texts in the input strings that follows the pattern and replace ONLY the match group 1. For example I have the regex pattern and the string to be applied on as shown below. The replacement string is "<---->"
Pattern p = Pattern.compile("\\w*(lan)\\w+");
Matcher m = p.matcher("plan plans lander planitia");
The expected result is
plan p<--->s <--->der p<--->itia
I tried following approaches
String test = "plan plans lander planitia";
Pattern p = Pattern.compile("\\w*(lan)\\w+");
Matcher m = p.matcher(test);
String result = "";
while(m.find()){
result = test.replaceAll(m.group(1),"<--->");
}
System.out.print(result);
This gives result as
p<---> p<--->s <--->der p<--->itia
Another approach
String test = "plan plans lander planitia";
Pattern p = Pattern.compile("\\w*(lan)\\w+");
Matcher m = p.matcher(test);
String result = "";
while(m.find()){
result = test.replaceAll("\\w*(lan)\\w+","<--->");
}
System.out.print(result);
Result is
plan <---> <---> <--->
I have gone through this link. Here the part of the string before the match is always constant and is "foo" but in my case it varies. Also I have looked at this and this but I am unable to apply any on the solutions given to my present scenario.
Any help is appreciated
You need to use the following pattern with capturing groups:
(\w*)lan(\w+)
^-1-^ ^-2-^
and replace with $1<--->$2
See the regex demo
The point is that we use a capturing group around the parts that we want to keep and just match what we want to discard.
Java demo:
String str = "plan plans lander planitia";
System.out.println(str.replaceAll("(\\w*)lan(\\w+)", "$1<--->$2"));
// => plan p<--->s <--->der p<--->itia
If you need to be able to replace the Group 1 and keep the rest, you may use the replace callback method emulation with Matcher#appendReplacement:
String text = "plan plans lander planitia";
String pattern = "\\w*(lan)\\w+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(0).replaceFirst(Pattern.quote(m.group(1)), "<--->"));
}
m.appendTail(sb); // append the rest of the contents
System.out.println(sb.toString());
// output => plan p<--->s <--->der p<--->itia
See another Java demo
Here, since we process a match by match, we should only replace the Group 1 contents once with replaceFirst, and since we replace the substring as a literal, we should Pattern.quote it.
To dynamically control the replacement value, use a find() loop with appendReplacement(), finalizing the result with appendTail().
That way you have full control of the replacement value. In your case, the pattern is the following, and you can get the positions indicated.
start(1)
↓ end(1)
↓ ↓
\\w*(lan)\\w+
↑ ↑
start() end()
You can then extract the values to keep.
String input = "plan plans lander planitia";
StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("\\w*(lan)\\w+").matcher(input);
while (m.find())
m.appendReplacement(buf, input.substring(m.start(), m.start(1)) +
"<--->" +
input.substring(m.end(1), m.end()));
String output = m.appendTail(buf).toString();
System.out.println(output);
Output
plan p<--->s <--->der p<--->itia
If you don't like that it uses the original string, you can use the matched substring instead.
StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("\\w*(lan)\\w+").matcher("plan plans lander planitia");
while (m.find()) {
String match = m.group();
int start = m.start();
m.appendReplacement(buf, match.substring(0, m.start(1) - start) +
"<--->" +
match.substring(m.end(1) - start, m.end() - start));
}
String output = m.appendTail(buf).toString();
While Wiktors explanation of the use of capturing groups is completely correct, you could avoid using them at all. The \\w* at the start of your pattern seems irrelevant, as you want to keep it anyways, so we can simply leave it out of the pattern. The check for a word-character after lan can be done using a lookahead, like (?=\w), so we actually only match lan in a pattern like "lan(?=\\w)" and can do a simple replace with "<--->" (or whatever you like).
I like others solutions. This is slightly optimalised bulletproof version:
public static void main (String [] args) {
int groupPosition = 1;
String replacement = "foo";
Pattern r = Pattern.compile("foo(bar)");
Matcher m = r.matcher("bar1234foobar1234bar");
StringBuffer sb = new StringBuffer();
while (m.find()) {
StringBuffer buf = new StringBuffer(m.group());
buf.replace(m.start(groupPosition)-m.start(), m.end(groupPosition)-m.start(), replacement);
m.appendReplacement(sb, buf.toString());
}
m.appendTail(sb);
System.out.println(sb.toString()); // result is "bar1234foofoo1234bar"
}

Get an array of Strings matching a pattern from a String

I have a long string let's say
I like this #computer and I want to buy it from #XXXMall.
I know the regular expression pattern is
Pattern tagMatcher = Pattern.compile("[#]+[A-Za-z0-9-_]+\\b");
Now i want to get all the hashtags in an array. How can i use this expression to get array of all hash tags from string something like
ArrayList hashtags = getArray(pattern, str)
You can write like?
private static List<String> getArray(Pattern tagMatcher, String str) {
Matcher m = tagMatcher.matcher(str);
List<String> l = new ArrayList<String>();
while(m.find()) {
String s = m.group(); //will give you "#computer"
s = s.substring(1); // will give you just "computer"
l.add(s);
}
return l;
}
Also you can use \\w- instead of A-Za-z0-9-_ making the regex [#]+[\\w]+\\b
This link would surely be helpful for achieving what you want.
It says:
The find() method searches for occurrences of the regular expressions
in the text passed to the Pattern.matcher(text) method, when the
Matcher was created. If multiple matches can be found in the text, the
find() method will find the first, and then for each subsequent call
to find() it will move to the next match.
The methods start() and end() will give the indexes into the text
where the found match starts and ends.
Example:
String text =
"This is the text which is to be searched " +
"for occurrences of the word 'is'.";
String patternString = "is";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
int count = 0;
while(matcher.find()) {
count++;
System.out.println("found: " + count + " : "
+ matcher.start() + " - " + matcher.end());
}
You got the hint now.
Here is one way, using Matcher
Pattern tagMatcher = Pattern.compile("#+[-\\w]+\\b");
Matcher m = tagMatcher.matcher(stringToMatch);
ArrayList<String> hashtags = new ArrayList<>();
while (m.find()) {
hashtags.add(m.group());
}
I took the liberty of simplifying your regex. # does not need to be in a character class. [A-Za-z0-9_] is the same as \w, so [A-Za-z0-9-_] is the same as [-\w]
You can use :
String val="I like this #computer and I want to buy it from #XXXMall.";
String REGEX = "(?<=#)[A-Za-z0-9-_]+";
List<String> list = new ArrayList<String>();
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(val);
while(matcher.find()){
list.add(matcher.group());
}
(?<=#) Positive Lookbehind - Assert that the character # literally be matched.
you can use the following code for getting the names
String saa = "#{akka}nikhil#{kumar}aaaaa";
Pattern regex = Pattern.compile("#\\{(.*?)\\}");
Matcher m = regex.matcher(saa);
while(m.find()) {
String s = m.group(1);
System.out.println(s);
}
It will print
akka
kumar

replace substring using regex

I have a string which contains many <xxx> values.
I want to retrive the value inside <>, do some manipulation and re-insert the new value into the string.
What I did is
input = This is <abc_d> a sample <ea1_j> input <lmk_02> string
while(input.matches(".*<.+[\S][^<]>.*"))
{
value = input.substring(input.indexOf("<") + 1, input.indexOf(">"));
//calculate manipulatedValue from value
input = input.replaceFirst("<.+>", manipulatedValue);
}
but after the first iteration, value contains abc_d> a sample <ea1_j> input <lmk_02. I believe indexOf(">") will give the first index of ">". Where did I go wrong?
This is a slightly easier way of accomplishing what you are trying to do:
String input = "This is <abc_d> a sample <ea1_j> input <lmk_02> string";
Matcher matcher = Pattern.compile("<([^>]*)>").matcher(input);
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(sb, manipulateValue(matcher.group(1)));
}
matcher.appendTail(sb);
System.out.println(sb.toString());
This is a good use case for the appendReplacement and appendTail idiom:
Pattern p = Pattern.compile("<([^>]+)>");
Matcher m = p.matcher(input);
StringBuffer out = new StringBuffer():
while(m.find()) {
String value = m.group(1);
// calculate manipulatedValue
m.appendReplacement(out, Matcher.quoteReplacement(manipulatedValue));
}
m.appendTail(out);
Try using an escape character \\ to the regex.

java regular expression find a string add it to array and then replace original

I have a string of text like this:
This is a[WAIT] test.
What I want to do is search the string for a substring that starts with [ and ends with ]
Each one I find I want to add it to an ArrayList and replace substring in original string with a ^
Here is my regex:
String regex_script = "/^\\[\\]$/"; //Match a string which starts with the character [ ending in the character ]
Here is what I have so far:
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile(regex_script); // Create a pattern to match
Matcher m = p.matcher(line); // Create a matcher with an input string
boolean result = m.find();
while(result) {
m.appendReplacement(sb, "^");
result = m.find();
}
m.appendTail(sb); // Add the last segment of input to the new String
how would I got about doing this? Thanks
you can do:
String regex_script = "\\[([^\\]]*)\\]";
String line = "This is a[WAIT] testThis is a[WAIT] test";
StringBuffer sb = new StringBuffer();
List<String> list = new ArrayList<String>(); //use to record
Pattern p = Pattern.compile(regex_script); // Create a pattern to match
Matcher m = p.matcher(line); // Create a matcher with an input string
while (m.find()) {
list.add(m.group(1));
m.appendReplacement(sb, "[^]");
}
m.appendTail(sb); // Add the last segment of input to the new String
System.out.println(sb.toString());
If you are searching a substring, don't use ^ and $. Those are for beginning and at end at a string (not a word) Try:
String regex_script = "/\[.*\]/";

Categories

Resources