A String will be of format [( 1.0N)-195( 1.0E)-195(28)-769.7(NESW)-1080.8(U)-617.9(43-047-30127)]
I need a regex to match to see if the string contains -XXX-XXX (where X is a digit)
Pattern p = Pattern.compile("(?=.*?(?:-[0-9][0-9][0-9]-[0-9][0-9][0-9]))");
if(p.matcher(a).matches())
{
System.out.println("Matched");
}
Also I've tried -[0-9][0-9][0-9]-[0-9][0-9][0-9] and (?=.*?-[0-9][0-9][0-9]-[0-9][0-9][0-9])
Nothing worked
A substring would be much easier, but (?:\\d{2})(-\\d{3}-\\d{5}) will match -XXX-XXXXX as the 1 group.
I'm assuming the 3 digits in the last number was a mistake. If not just change the 5 to a 3.
If you want to check if the string contains -3digits-3digits
String a = "43-037-30149";
Pattern p = Pattern.compile(".*(-[0-9]{3}-[0-9]{3})");
if(p.matcher(a).matches())
{
System.out.println("Matched");
}
why don't you use substring??
String b = a.substring(2,9);
or this one:
String c = a.substring(a.indexOf('-'), a.indexOf('-') + 8);
making "only" a substring would also be much more efficient! ;)
Related
I need to split a string based on a pattern and again i need to merge it back on a portion of string.
for ex: Below is the actual and expected strings.
String actualstr="abc.def.ghi.jkl.mno";
String expectedstr="abc.mno";
When i use below, i can store in a Array and iterate over to get it back. Is there anyway it can be done simple and efficient than below.
String[] splited = actualstr.split("[\\.\\.\\.\\.\\.\\s]+");
Though i can acess the string based on index, is there any other way to do this easily. Please advise.
You do not understand how regexes work.
Here is your regex without the escapes: [\.\.\.\.\.\s]+
You have a character class ([]). Which means there is no reason to have more than one . in it. You also don't need to escape .s in a char class.
Here is an equivalent regex to your regex: [.\s]+. As a Java String that's: "[.\\s]+".
You can do .split("regex") on your string to get an array. It's very simple to get a solution from that point.
I would use a replaceAll in this case
String actualstr="abc.def.ghi.jkl.mno";
String str = actualstr.replaceAll("\\..*\\.", ".");
This will replace everything with the first and last . with a .
You could also use split
String[] parts = actualString.split("\\.");
string str = parts[0]+"."+parts[parts.length-1]; // first and last word
public static String merge(String string, String delimiter, int... partnumbers)
{
String[] parts = string.split(delimiter);
String result = "";
for ( int x = 0 ; x < partnumbers.length ; x ++ )
{
result += result.length() > 0 ? delimiter.replaceAll("\\\\","") : "";
result += parts[partnumbers[x]];
}
return result;
}
and then use it like:
merge("abc.def.ghi.jkl.mno", "\\.", 0, 4);
I would do it this way
Pattern pattern = Pattern.compile("(\\w*\\.).*\\.(\\w*)");
Matcher matcher = pattern.matcher("abc.def.ghi.jkl.mno");
if (matcher.matches()) {
System.out.println(matcher.group(1) + matcher.group(2));
}
If you can cache the result of
Pattern.compile("(\\w*\\.).*\\.(\\w*)")
and reuse "pattern" all over again this code will be very efficient as pattern compilation is the most expensive. java.lang.String.split() method that other answers suggest uses same Pattern.compile() internally if the pattern length is greater then 1. Meaning that it will do this expensive operation of Pattern compilation on each invocation of the method. See java.util.regex - importance of Pattern.compile()?. So it is much better to have the Pattern compiled and cached and reused.
matcher.group(1) refers to the first group of () which is "(\w*\.)"
matcher.group(2) refers to the second one which is "(\w*)"
even though we don't use it here but just to note that group(0) is the match for the whole regex.
Its basically about getting string value between two characters. SO has many questions related to this. Like:
How to get a part of a string in java?
How to get a string between two characters?
Extract string between two strings in java
and more.
But I felt it quiet confusing while dealing with multiple dots in the string and getting the value between certain two dots.
I have got the package name as :
au.com.newline.myact
I need to get the value between "com." and the next "dot(.)". In this case "newline". I tried
Pattern pattern = Pattern.compile("com.(.*).");
Matcher matcher = pattern.matcher(beforeTask);
while (matcher.find()) {
int ct = matcher.group();
I tried using substrings and IndexOf also. But couldn't get the intended answer. Because the package name in android varies by different number of dots and characters, I cannot use fixed index. Please suggest any idea.
As you probably know (based on .* part in your regex) dot . is special character in regular expressions representing any character (except line separators). So to actually make dot represent only dot you need to escape it. To do so you can place \ before it, or place it inside character class [.].
Also to get only part from parenthesis (.*) you need to select it with proper group index which in your case is 1.
So try with
String beforeTask = "au.com.newline.myact";
Pattern pattern = Pattern.compile("com[.](.*)[.]");
Matcher matcher = pattern.matcher(beforeTask);
while (matcher.find()) {
String ct = matcher.group(1);//remember that regex finds Strings, not int
System.out.println(ct);
}
Output: newline
If you want to get only one element before next . then you need to change greedy behaviour of * quantifier in .* to reluctant by adding ? after it like
Pattern pattern = Pattern.compile("com[.](.*?)[.]");
// ^
Another approach is instead of .* accepting only non-dot characters. They can be represented by negated character class: [^.]*
Pattern pattern = Pattern.compile("com[.]([^.]*)[.]");
If you don't want to use regex you can simply use indexOf method to locate positions of com. and next . after it. Then you can simply substring what you want.
String beforeTask = "au.com.newline.myact.modelact";
int start = beforeTask.indexOf("com.") + 4; // +4 since we also want to skip 'com.' part
int end = beforeTask.indexOf(".", start); //find next `.` after start index
String resutl = beforeTask.substring(start, end);
System.out.println(resutl);
You can use reflections to get the name of any class. For example:
If I have a class Runner in com.some.package and I can run
Runner.class.toString() // string is "com.some.package.Runner"
to get the full name of the class which happens to have a package name inside.
TO get something after 'com' you can use Runner.class.toString().split(".") and then iterate over the returned array with boolean flag
All you have to do is split the strings by "." and then iterate through them until you find one that equals "com". The next string in the array will be what you want.
So your code would look something like:
String[] parts = packageName.split("\\.");
int i = 0;
for(String part : parts) {
if(part.equals("com")
break;
}
++i;
}
String result = parts[i+1];
private String getStringAfterComDot(String packageName) {
String strArr[] = packageName.split("\\.");
for(int i=0; i<strArr.length; i++){
if(strArr[i].equals("com"))
return strArr[i+1];
}
return "";
}
I have done heaps of projects before dealing with websites scraping and I
just have to create my own function/utils to get the job done. Regex might
be an overkill sometimes if you just want to extract a substring from
a given string like the one you have. Below is the function I normally
use to do this kind of task.
private String GetValueFromText(String sText, String sBefore, String sAfter)
{
String sRetValue = "";
int nPos = sText.indexOf(sBefore);
if ( nPos > -1 )
{
int nLast = sText.indexOf(sAfter,nPos+sBefore.length()+1);
if ( nLast > -1)
{
sRetValue = sText.substring(nPos+sBefore.length(),nLast);
}
}
return sRetValue;
}
To use it just do the following:
String sValue = GetValueFromText("au.com.newline.myact", ".com.", ".");
I'm attempting to make the following replacement in java
#Test
public void testReplace(){
String str = "1JU3C_2.27.CBT";
String find = "(\\d*)\\.(\\d*)";
String replace = "$1,$2";
String modified = str.replaceAll(find, replace);
System.out.println(modified);
assertEquals("1JU3C_2,27.CBT", modified); //fails
}
However both full stops seem to be getting replaced. I'm looking at replacing only the numeric decimal. (i.e expecting output 1JU3C_2,27.CBT)
Use (\\d+)\\.(\\d+) instead of (\\d*)\\.(\\d*).
Your regex asks to replace zero or more digits followed by a dot, followed by zero or more digits. So . in .CBT is matched as it has a dot with zero digits on both sides.
1JU3C_2.27.CBT has two dots with zero or more digits on both sides.
If you want to convert string like 5.67.8 to 5,67,8 use lazy matching as (\\d+?)\\.(\\d+?).
*
stands for zero or more times, try replacing it with
+
Instead do this:
public void testReplace()
{
String str = "1JU3C_2.27.CBT";
String modified = str.replaceFirst("[.]", ",");
System.out.println(modified);
assertEquals("1JU3C_2,27.CBT", modified);
}
Hi please help me out in getting regular expression for the
following requirement
I have string type as
String vStr = "Every 1 nature(s) - Universe: (Air,Earth,Water sea,Fire)";
String sStr = "Every 1 form(s) - Earth: (Air,Fire) ";
from these strings after using regex I need to get values as "Air,Earth,Water sea,Fire" and "Air,Fire"
that means after
String vStrRegex ="Air,Earth,Water sea,Fire";
String sStrRegex ="Air,Fire";
All the strings that are input will be seperated by ":" and values needed are inside brackets always
Thanks
The regular expression would be something like this:
: \((.*?)\)
Spelt out:
Pattern p = Pattern.compile(": \\((.*?)\\)");
Matcher m = p.matcher(vStr);
// ...
String result = m.group(1);
This will capture the content of the parentheses as the first capture group.
Try the following:
\((.*)\)\s*$
The ending $ is important, otherwise you'll accidentally match the "(s)".
If you have each string separately, try this expression: \(([^\(]*)\)\s*$
This would get you the content of the last pair of brackets, as group 1.
If the strings are concatenated by : try to split them first.
Ask yourself if you really need a regex. Does the text you need always appear within the last two parentheses? If so, you can keep it simple and use substring instead:
String vStr = "Every 1 nature(s) - Universe: (Air,Earth,Water sea,Fire)";
int lastOpeningParens = vStr.lastIndexOf('(');
int lastClosingParens = vStr.lastIndexOf(')');
String text = vStr.substring(lastOpeningParens + 1, lastClosingParens);
This is much more readable than a regex.
I assume that there are only whitespace characters between : and the opening bracket (:
Pattern regex = Pattern.compile(":\\s+\\((.+)\\)");
You'll find your results in capturing group 1.
Try this regex:
.*\((.*)\)
$1 will contain the required string
I have a string in the following format, I only need to extract the /jspFolderTestSecondLast/jspFolderTestLast,
which is the second last seperated by /.
www.name.com/jspFolderTestOne/jspFolderTestTwo/jspFolderTestAndmanyMore/jspFolderTestSecondLast/jspFolderTestLast
/jspFolderTestSecondLast/jspFolderTestLast can be varied in length but always gonna be separated by secong last /.
Any help is appreciated.
Thanks
String s = "www.name.com/jspFolderTestOne/jspFolderTestTwo/jspFolderTestAndmanyMore/jspFolderTestSecondLast/jspFolderTestLast"
String[] parts = s.split("/");
String whatYouWant = parts[parts.length-2] +"/" + parts[parts.length-1]
You don't need any regexes for that, since you can just split the string on '/' and get two last array indexes. But here's the regex anyway:
^.+(/[^/]+)(/[^/]+)$
$1 contains the first and $2 contains the second block
String str = "www.name.com/jspFolderTestOne/jspFolderTestTwo/jspFolderTestAndmanyMore/jspFolderTestSecondLast/jspFolderTestLast";
String are[] = str.split("/");//may be you need to add escape here
//take last two parts
Pattern p = Pattern.compile(".*(/[^/]+/[^/]+)$");
Matcher m = p.matcher("a/b/c/d.txt");
if( m.matches() ) {
System.out.println(m.group(1));
}
this is the javascript version:
"www.name.com/jspFolderTestOne/jspFolderTestTwo/jspFolderTestAndmanyMore/jspFolderTestSecondLast/jspFolderTestLast".search(/\/[^\/]*\/[^\/]*$/)
or you can group them nicely:
(/(\/[^\/]*)(\/[^\/]*)$/)