I have a list of strings: ab10sdj, ba1wqa, cd03asce, dfasc, etc. I'm looking to get the group of digits from the strings that start either with ab, or with ba.
So if a string starts with ab/ba, I need the group of digits right after them. If there a way for me to achieve this via a java matcher/regex?
Apologies for posting this as an answer but my current reputation level doesn't allow me 'comment' ... yet :)
As apposed to simply giving an answer to a relatively simple problem (without insulting your intelligence), I can help with diagnosing a solution. Try thinking the problem through in your mind, step by step. That is:
How do you test for the first 2 characters in a string?
If the test to point 1 passes (IE, they are ab or ba), how do you then process the rest of the string to test for 'digits' only?
How do you stop processing the 'digits' when you reach a non-digit?
Once you have your ab/ba prefix, only extracted the 'digits' immediately following the test condition, how will you handle the digits extracted?
Before considering placing the digits in a primitive type, you may wish to consider how many digits one may expect?
All the best with your code!
You can try regex like this :
public static void main(String[] args) {
// ab10sdj, ba1wqa, cd03asce, dfasc
String s1 = "ab10sdj";
String s2 = "ba1wqa";
String s3 = "cd03asce";
String s4 = "dfasc";
String pattern = "^(ab|ba)(\\d+).*";
System.out.println(s1.replaceAll(pattern, "$2")); // output 10
System.out.println(s2.replaceAll(pattern, "$2")); // output 1
System.out.println(s3.replaceAll(pattern, "$2")); // output cd03asce i.e, no change
System.out.println(s4.replaceAll(pattern, "$2")); // output dfasc i.e, no change
}
Related
I am working with some legacy code that has a static method call which we need to remove from our source tree.
The existing code is as follows:
Logger.getInstance(JdkUtil.forceInit(SomeBusiness.class));
What we need to end up with is:
Logger.getInstance(SomeBusiness.class);
I've spent all day today trying to figure out how to do that replacement. Since I have very little experience with regular expressions, I have only been able to come up with a pattern that matches the source string.
The pattern JdkUtil.forceInit([a-zA-Z_0-9]*.class) finds matches on the input string I am providing. I've tested this at https://www.freeformatter.com/java-regex-tester.html
So if anyone can post a Java solution to this, I would really appreciate it.
Below is some Groovy code that I have so far. What I am missing is to how correctly replacement explained above.
String source = 'Logger.getInstance(JdkUtil.forceInit(RtpRuleEngineCompiledImpl.class))'
String regexpPattern = 'JdkUtil.forceInit\\([a-zA-Z_0-9\\)]*.class\\)'
String replaced = source.replaceFirst(regexpPattern, 'hello')
println replaced
When I run the above code I get the following output:
Logger.getInstance(hello)
Obviously 'hello' is just for testing.
Thanks in advance to anyone who can give me some suggestions.
You'll likely want to do something such as:
class StackOverflow {
public static void main(String[] args) {
String source = "Logger.getInstance(JdkUtil.forceInit(RtpRuleEngineCompiledImpl.class))";
String regexpPattern = "JdkUtil.forceInit\\(([a-zA-Z_0-9]*.class)\\)";
String replaced = source.replaceFirst(regexpPattern, "$1");
System.out.println(replaced);
}
}
Result:
Logger.getInstance(RtpRuleEngineCompiledImpl.class)
The capture group ($1) replaces the entire string which was within the parentheses.
I am implementing as automation script and following BDD frame work with selenium webdriver.
Acceptance Criteria:
Scenario: Members name
Given that the web page is displayed
When the user clicks anywhere on the member row
Then member First Name, Middle Initial, Last Name will be displayed
And Member First Name, Middle Initial, Last name display in Camel case
Would you pleas let me know how to validate the Camel case for displayed information in web page? Like "Jhon D Hamton".
By using WordUtils in the Apache Commons lang library:
Specifically, the capitalizeFully(String str, char[] delimiters) method should do the job:
String blah = "LORD_OF_THE_RINGS";
assertEquals("LordOfTheRings", WordUtils.capitalizeFully(blah, new char[]{'_'}).replaceAll("_", ""));
Resource Link:
What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?
Well, assuming you can grab your string, I'd split it then check that the first letter is uppercase:
boolean isCamelCase(String s) {
String[] split_string = s.split(" ");
for(int i=0;i<split_string.length;i++) {
if(!Character.isUpperCase(split_string[i].charAt(0))){
return false;
}
}
return true;
}
If you know how, or are able to get the entire name as a string, you can use the following Regex to assert that it is camel case:
[A-Z]([A-Z0-9]*[a-z][a-z0-9]*[A-Z]|[a-z0-9]*[A-Z][A-Z0-9]*[a-z])[A-Za-z0-9]*
This matches strings that start with an uppercase letter, contain only letters and numbers, and contain at least one lowercase letter and at least one other uppercase letter.
For Java, you want to call the String class's matches() method, which returns true or false:
boolean doesItMatch = yourString.matches('theRegexAbove');
I have the following requirement where in I need to do few things only if the given string ends in "Y" or "Years" or "YEARS".
I tried doing it using regex like this.
String text=1.5Y;
if(Pattern.matches("Y$",text) || Pattern.matches("YEARS$",text) || Pattern.matches("Years",text))
{
//do
}
However this is getting failed.
Can someone point me where I have gone wrong or suggest me any other feasible method.
EDIT:
Thanks.That helps.
Finally I have used "(?i)^.*Y(ears)?$| (?i)^.*M(onths)?$".
But I want to make more changes to make it perfect.
Let's say I have many strings.
Ideally only strings like 1.5Y or 0.5-3.5Y or 2.5/2.5-4.5Y should pass if check.
It can be number of years(Ex:2.5y) or the period of years(2.5-3.5y) or the no of years/period of years(Ex.2.5/3.5-4.5Y) nothing more.
More Examples:
--------------
Y -should fail;
MY - should fail;
1.5CY - should fail;
1.5Y-2.5Y should fail;
1.5-2.5Y should pass;
1.5Y/2.5-3.5Y should fail;
1.5/2.5-3.5Y should pass;
You don't need a regex here:
if(text.endsWith("Y") || ...)
matches method attempts to match full input so use:
^.*Y$
for your first pattern.
btw you can use a single regex for all 3 cases:
if (text.matches( "(?i)^.*Y(ears)?$" ) ) {...}
(?i) does ignore case match.
.*(?:Y|YEARS|Years)$
You can directly use this .Match matches from beginning.So yours is failing.
You can simply use the regex pattern:
if (Pattern.matches(".*(Y|YEARS|Years)$",text)) {/*do something*/}
/((?!0)\d+|0)(.\d+)?(?:years|year|y)/gi
https://regex101.com/r/gJ6xD2/2
var text = "1.6y 1.5years 1year 1.5h";
text.match(/((?!0)\d+|0)(\.\d+)?(?:years|year|y)/gi);
Result["1.6y", "1.5years", "1year"]
(?=^(0\.\d+|[1-9](?:\d+)?(?:\.\d+)?)(?:(\s+)?[\/-](\s+)?(?:0\.\d+|[1-9](?:\d+)?(?:\.\d+)?))*(?:\s+)?(?:y(?:(ea)?rs|ears?)?|m(?:onths?)?)$).*
https://regex101.com/r/kL7rQ1/3
Only thing I wasn't sure "2.3 - 4 / 6.2 y" format is acceptable or not, so I've included it.
I am having regex expression problem. need helps from regex experts!
It's fairly simple but I can't get it to work.
I know if I want to check the starting of a text, I should use ^
and ending of the text, I should use $
I want to replace [quote] to <a>quote</a>.
This doesn't seems to work..
String test = "this is a [quote]"
test.replaceAll("^\\[", "<a>");
test.replaceAll("\\]$", "</a>");
I want the string to become "this is a <a>quote</a>"..
If you want to replace [ and ] with pair, you need to replace them in one time.
String test = "this [test] is a [quote]";
String result = test.replaceAll("\\[([^\\]]+)\\]", "<a>$1</a>");
^ implies that you are looking for something at the beginning of the string. However [ does not appear at the beginning of the string, so you will not have a match. Just do:
test.replaceAll("\\[", "<a>");
test.replaceAll("\\]", "</a>");
Also, you cannot modify a String in-place. you'll have to assign the output to something. You can do:
test = test.replaceAll("\\[", "<a>").replaceAll("\\]", "</a>");
That is if you still want to use the variable test.
I have the following REGEX that I'm serving up to java via an xml file.
[a-zA-Z -\(\) \-]+
This regex is used to validate server side and client side (via javascript) and works pretty well at allowing only alphabetic content and a few other characters...
My problem is that it will also allow zero lenth strings / empty through.
Does anyone have a simple and yet elegant solution to this?
I already tried...
[a-zA-Z -\(\) \-]{1,}+
but that didn;t seem to work.
Cheers!
UPDATE FOLLOWING INVESTIGATION
It appears the code I provided does in fact work...
String inputStr = " ";
String pattern = "[a-zA-Z -\\(\\) \\-]+";
boolean patternMatched = java.util.regex.Pattern.matches(pattern, inputStr);
if ( patternMatched ){
out.println("Pattern MATCHED");
}else{
out.println("NOT MATCHED");
}
After looking at this more closely I think the problem may well be within the logic of some of my java bean coding... It appears the regex is dropped out at the point where the string parse should take place, thereby allowing empty strings to be submitted... And also any other string... EEJIT that I am...
Cheers for the help in peer reviewing my initial stupid though....!
Have you tried this:
[a-zA-Z -\(\) \-]+