I am using StringUtils (import org.apache.commons.lang3.StringUtils;) library to split string like:
String str = "ZXCVFMS2ZZ1012ZZ1012ZZ1000ZZ0923ZZ0990ZZ0990ZZ0990ZZ1020DEFZXCVFMS3ZZ1012ZZ1012ZZ1000ZZ0923ZZ0990ZZ0990ZZ0990ZZ1020DEFZXCVFMERRORDEF";
I need to take out string start with zxcv* and end with *def as
String tmp1 = "ZXCVFMS2ZZ1012ZZ1012ZZ1000ZZ0923ZZ0990ZZ0990ZZ0990ZZ1020DEF";
String tmp2 = "ZXCVFMS3ZZ1012ZZ1012ZZ1000ZZ0923ZZ0990ZZ0990ZZ0990ZZ1020DEF";
any help?
Solution thanks to #assylias :
Pattern p = Pattern.compile("ZXCV.*?DEF");
Matcher m = p.matcher(str);
List<String> result = new ArrayList<> ();
while (m.find()) {
result.add(m.group());
}
How about using replaceAll?
String tmp = str.replaceAll(".*(zxcv.*def).*", "$1"); //zxcvVariableCanChancedef
UPDATE following your edit
if you have a repeating pattern, you could use a Matcher - to avoid matching the whole string use the ? quantifier to make the match lazy.
Pattern p = Pattern.compile("zxcv.*?def");
String input = "15684zxcvVariableCanChancedefABCDEND15684zxcvVariableCanChancedefABCDEND";
Matcher m = p.matcher(input);
List<String> result = new ArrayList<> ();
while (m.find()) {
result.add(m.group());
}
This can be done without any additional libraries using core java.util.regex functionality. For example:
String str = "15684zxcvVariableCanChancedefABCDEND";
Pattern pattern = Pattern.compile(".*(zxcv.*def).*");
Matcher matcher = pattern.matcher(str);
if (matcher.matches()) {
System.out.println(matcher.group(1)); // ==> zxcvVariableCanChancedef
}
String line = "15684zxcvAAAAAAAncedefABCDEND15684zxcvBBBBBBBBBBdefABCDEND";
Last occurrence :
Matcher matcher = Pattern.compile(".*(zxcv.*def).*").matcher(line);
String tmp = matcher.find() ? matcher.group(1) : null;
System.out.println(tmp);
First occurence :
Matcher matcher = Pattern.compile(".*?(zxcv.*?def).*").matcher(line);
Biggest occurence (from first zxcv to last def) :
Matcher matcher = Pattern.compile(".*?(zxcv.*def).*").matcher(line);
All occurrences
Matcher matcher = Pattern.compile(".*?(zxcv.*?def)").matcher(line);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
I am not sure about it because I wrote it using a text document, I don't have any java IDE in this computer. I hope it helps
public String XXX()
{
int firstStorage = 0;
int secondStorage = 0;
for (int i = 0 ; i < tmp.lenght() < i++)
{
if( tmp.substring(i,i+4).equals("zxcv"))
{
firstStorage = i;
break;
}
}
for (int i = firstStorage ; i < tmp.lenght() < i++)
{
if( tmp.substring(i,i+3).equals("def"))
{
secondStorage = i + 2;
break;
}
}
return tmp.substring(firstStorage, secondStorage + 1);
}
Let me know if it is working or not. Have a nice day !!
String str = "15684zxcvVariableCanChancedefABCDEND15684zxcvVariableCanChancedefABCDEND";
List<string> strList = new List<string>();
while (str.IndexOf("zxc") >= 0 && str.IndexOf("def") >= 0)
{
var startIndex = str.IndexOf("zxc");
var stopIndex = str.IndexOf("def");
var item = str.Substring(startIndex, stopIndex - startIndex + 3);
strList.Add(item);
str = str.Substring(0, startIndex) + str.Substring(stopIndex+3);
}
Related
i am beginner in java , I have the below
flybirdy_blue.co
strongwolf_red.po
I want such result
blue
red
String[] parts = csvFile.split("_");
String color = parts[1];
but it give me wrong result
you can use it:
String s = "flybirdy_blue.po";
Pattern pattern = Pattern.compile("(_)(.+)(\\.)");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
System.out.println(matcher.group(2)); //red
}
you are splitting around "_" , but you need to further split around "." ..
so try ,
String[] parts = csvFile.split("_");
String color = parts[1].split(".")[1];
Or you could try splitting around _ & . at the same time using "[]" explained here in the "character classes" section:
String[] parts = csvFile.split("[_.]");
String color = parts[1];
Maybe you should write your own function for better understanding:
public ArrayList<String> splitMyString(String wholeString, char[] splitHere){
ArrayList<String> response = new ArrayList<String>();
String temp ="";
boolean skip = false;
for(int i = 0 ; i < wholeString.length(); i++){
for(int j = 0 ; j < splitHere.length; j++){
if(wholeString.charAt(i) == splitHere[j]){
response.add(temp);
temp="";
skip = true;
}
}
if(skip != true){
temp = temp +wholeString.charAt(i);
}else{
skip = false;
}
}
response.add(temp);
return response;
}
You can use the substring() function to get the value between "_" and "." as follows.
Here you go :
String firstcsvFile = "flybirdy_blue.co";
String secondcsvFile = "strongwolf_red.po";
String result = firstcsvFile.substring(firstcsvFile.indexOf("_") + 1, firstcsvFile.indexOf("."));
String result2 = secondcsvFile.substring(secondcsvFile.indexOf("_") + 1, secondcsvFile.indexOf("."));
System.out.println(result);
System.out.println(result2);
Output
blue
red
I want to find a single regex which matches the longest numerical string in a URL.
I.e for the URL: http://stackoverflow.com/1234/questions/123456789/ask, I would like it to return : 123456789
I thought I could use : ([\d]+)
However this returns the first match from the left, not the longest.
Any ideas :) ?
This regex will be used as an input to a strategy pattern, which extracts certain characteristics from urls:
public static String parse(String url, String RegEx) {
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(url);
if (m.find()) {
return m.group(1);
}
return null;
}
So it would be much tidier if I could use a single regex. :( –
Don't use regex. Just iterate the characters:
String longest = 0;
int i = 0;
while (i < str.length()) {
while (i < str.length() && !Character.isDigit(str.charAt(i))) {
++i;
}
int start = i;
while (i < str.length() && Character.isDigit(str.charAt(i))) {
++i;
}
if (i - start > longest.length()) {
longest = str.substring(start, i);
}
}
#Andy already gave a non-regex answer, which is probably faster, but if you want to use regex, you must, as #Jan points out, add logic, e.g.:
public String findLongestNumber(String input) {
String longestMatch = "";
int maxLength = 0;
Matcher m = Pattern.compile("([\\d]+)").matcher(input);
while (m.find()) {
String currentMatch = m.group();
int currentLength = currentMatch.length();
if (currentLength > maxLength) {
maxLength = currentLength;
longestMatch = currentMatch;
}
}
return longestMatch;
}
t
Not possible with pure Regex, however I would do it this way (using Stream Max and Regex) :
String url = "http://stackoverflow.com/1234/questions/123456789/ask";
Pattern biggest = Pattern.compile("/(\\d+)/");
Matcher m = biggest.matcher(url);
List<String> matches = new ArrayList<>();
while(m.find()){
matches.add(m.group(1));
}
System.out.println(matches.parallelStream().max((String a, String b) -> Integer.compare(a.length(), b.length())).get());
Will print : 123456789
I have a string :
154545K->12345K(524288K)
Suppose I want to extract numbers from this string.
The string contains the group 154545 at position 0, 12345 at position 1 and 524288 at position 2.
Using regex \\d+, I need to extract 12345 which is at position 1.
I am getting the desired result using this :
String lString = "154545K->12345K(524288K)";
Pattern lPattern = Pattern.compile("\\d+");
Matcher lMatcher = lPattern.matcher(lString);
String lOutput = "";
int lPosition = 1;
int lGroupCount = 0;
while(lMatcher.find()) {
if(lGroupCount == lPosition) {
lOutput = lMatcher.group();
break;
}
else {
lGroupCount++;
}
}
System.out.println(lOutput);
But, is there any other simple and direct way to achieve this keeping the regex same \\d+(without using the group counter)?
try this
String d1 = "154545K->12345K(524288K)".replaceAll("(\\d+)\\D+(\\d+).*", "$1");
If you expect your number to be at the position 1, then you can use find(int start) method like this
if (lMatcher.find(1) && lMatcher.start() == 1) {
// Found lMatcher.group()
}
You can also convert your loop into for loop to get ride of some boilerplate code
String lString = "154540K->12341K(524288K)";
Pattern lPattern = Pattern.compile("\\d+");
Matcher lMatcher = lPattern.matcher(lString);
int lPosition = 2;
for (int i = 0; i < lPosition && lMatcher.find(); i++) {}
if (!lMatcher.hitEnd()) {
System.out.println(lMatcher.group());
}
I have string p[name]=[1111];[2222] and i need to take from it 3 parts p[name]=, [1111] and [2222]. String can be different like p[name]=[1111] or p[name]=[1111];[2222,[1,2,3],1];[3333]
I'm trying to use regex for it, but can't find working solution.
My regex is
(p\\[[a-zA-Z0-9]+\\]=)(?:(\\[.[^;]+\\]);?)+
When i run this code i have only two groups
Pattern p = Pattern.compile("(p\\[[a-zA-Z0-9^=]+\\]=)(?:;*(\\[.[^;]+\\]))+");
Matcher m = p.matcher("p[name]=[1111];[2222]");
if (m.find()) {
for(int i = 1, l = m.groupCount(); i <= l; ++i) {
System.out.println(m.group(i));
}
}
Result is
p[name]=
[2222]
Why not simply do this?
Pattern p = Pattern.compile("p\\[[a-z0-9]+]=|\\[[0-9]+]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("p[name]=[1111];[2222]");
while(m.find()) {
System.out.println(m.group());
}
However, if you want to check the string structure at the same time, you can use this kind of pattern:
Pattern p = Pattern.compile("(p\\[[a-z0-9]+]=)|\\G(?<!^)(\\[[0-9]+])(?:;|$)", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("p[name]=[1111];[2222]");
while(m.find()) {
System.out.println((m.group(1))? m.group(1) : m.group(2));
}
I can give you this regex. That should also work with this: p[name]=[1111];[2222,[1,2,3],1]
Pattern p = Pattern.compile("([p]+)|\[[a-z0-9\,\[\]]+\]");
Matcher m = p.matcher("p[name]=[1111];[2222]");
if (m.find()) {
for(int i = 1, l = m.groupCount(); i <= l; ++i) {
System.out.println(m.group(i));
}
}
Which regular expression in java can do these conversions?
"1.54.0.21" to "01540021"
or
"33.5.10.6" to "33051006"
I need to replace .# with 0# and .## with ##
You could try something like...
StringBuilder output = new StringBuilder(8);
String input = "1.54.0.21";
Pattern p = Pattern.compile("\\d+");
Matcher matcher = p.matcher(input);
while (matcher.find()) {
String group = matcher.group();
if (group.length() < 2) {
output.append("0");
}
output.append(group);
}
System.out.println(input);
System.out.println(output);
Which outputs...
1.54.0.21
01540021
Without Regex :
http://rextester.com/LGXETU62790
public static void main(String args[])
{
String str1 = "33.5.9.6";
String str2 = "1.54.0.21";
System.out.println(transform(str1));
System.out.println(transform(str2));
}
private static String transform(String str){
String[] splitted = str.split("\\.");
StringBuilder build = new StringBuilder();
for(String s : splitted){
build.append(String.format("%02d", Integer.parseInt(s)));
}
return build.toString();
}
The only functionality of a regular expression is to match a certain pattern of characters inside a string (or multiline strings).
A regular expression can be used in a find and replace Pattern but only to find the strings you are interested in. When they are found , a Split(), Remove(), Replace(), function will better do it's purpose.
I recommend you : http://gskinner.com/RegExr/
This is an online tool for matching strings with regular expression, and also learning the patterns.
public String getToken(String elem) {
return (elem.size() == 1) ? ("0" + elem) : elem;
}
String[] a = "1.54.0.21".split("\\.");
String o = "", e;
int i = 0, len = a.size();
for (i = 0; i < len; i++) {
o = o + getToken(a[i]);
}
System.out.println(o); //01540021