Regex submitting with empty string - java

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 -\(\) \-]+

Related

Need to get Particular word using java Regex

I want to get one particular word using regex in java. thanks
in the below paragraph, I need to find the network interface name
resource "azurerm_network_interface" "nic_LinuxVMCent-nhi" {
name = "nic_LinuxVMCent-nhi"
location = azurerm_resource_group.main.location
resource_group_name = azurerm_resource_group.main.name
ip_configuration {
name = "pubIP_LinuxVMCent-nhi"
subnet_id = azurerm_subnet.sub_wind12VM-PtN.id
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.pubIP_LinuxVMCent-nhi.id
}
}
data "azurerm_snapshot" "snapLinuxVMCent-nhi" {
name = "CentOS76New-0"
resource_group_name = "SaaSworkloadsnaps"
}
Expected Result Ex:
nic_LinuxVMCent-nhi
This is a multi-line bit of text. However, there appears to be a line which you could recognise with a regex:
resource "azurerm_network_interface" "nic_LinuxVMCent-nhi" {
So the regex for that would be ^resource "azurerm_network_interface" "([^"]+)" {$ - see https://regexr.com/67ldb
You can use Matcher.match to see if the any line matches this expression and if it does then matcher.group(1) will be the value you're looking for.
you can use this regex to find the network interface name:
(?<=resource \"azurerm_network_interface\" \").+(?=\" {)
I have used lookahead to find the name.
Also, here's a link to regex101:
Link
I don't know network interfaces so,
This regex solution is specific to "azurerm_network_interface."
If you need any additional help, please comment down below.
Cheers :)

Keep the same case when replacing words in Java

My goal is to correct common grammar errors in messages. Here's what I currently have written:
#EventHandler
public void onChat(AsyncPlayerChatEvent event){
String message = event.getMessage().replaceAll("(?i)dont", "don't")
.replaceAll("(?i)youre", "you're");
event.setMessage(message);
}
This works to replace dont with don't, and youre with you're. The issue is that DONT is replaced with don't, rather than DON'T.
How would I execute this replacement while preserving case?
Use capturing groups:
> "DoNt".replaceAll("(?i)\\b(don)(t)\\b", "$1'$2")
"DoN't" (String)
> "YoUrE".replaceAll("(?i)\\b(you)(re)\\b", "$1'$2")
"YoU'rE" (String)
You should also use \b for a word boundary, so you don't inadvertently change words like "orthodontist" into "orthodon'tist".

java regular expression partial replace

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.

Check if a string ends in is valid or not in java using regex

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.

How to write a Ruby-regex pattern in Java (includes recursive named-grouping)?

well... i have a file containing tintin-script. Now i already managed to grab all actions and substitutions from it to show them properly ordered on a website using Ruby, which helps me to keep an overview.
Example TINTIN-script
#substitution {You tell {([a-zA-Z,\-\ ]*)}, %*$}
{<279>[<269> $sysdate[1]<279>, <269>$systime<279> |<219> Tell <279>] <269>to <219>%2<279> : <219>%3}
{4}
#substitution {{([a-zA-Z,\-\ ]*)} tells you, %*$}
{<279>[<269> $sysdate[1]<279>, <269>$systime<279> |<119> Tell <279>] <269>from <119>%2<279> : <119>%3}
{2}
#action {Your muscles suddenly relax, and your nimbleness is gone.}
{
#if {$sw_keepaon}
{
aon;
};
} {5}
#action {xxxxx}
{
#if {$sw_keepfamiliar}
{
familiar $familiar;
};
} {5}
To grab them in my Ruby-App i read my script-file into a varibable 'input' and then use the following pattern to scan the 'input'
pattern = /(?<braces>{([^{}]|\g<braces>)*}){0}^#(?<type>action|substitution)\s*(?<b1>\g<braces>)\s*(?<b2>\g<braces>)\s*(?<b3>\g<braces>)/im
input = ""
File.open("/home/igambin/lmud/lmud.tt") { |file| input = file.read }
input.scan(pattern) { |prio, type, pattern, code|
## here i usually create objects, but for simplicity only output now
puts "Type : #{type}"
puts "Pattern : #{pattern}"
puts "Priority: #{prio}"
puts "Code :\n#{code}"
puts
}
Now my idea was to use the netbeans platform to write a module to not only keep an overview but also to assist editing the tintin script file. So opening the file in an Editor-Window I still need to parse the tintin-file and have all 'actions' and 'substitutions' from the file grabbed and displayed in an eTable, in wich I could dbl-click on one item to open a modification-window.
I've setup the module and got everything ready so far, i just can't figure out how to translate the ruby-regex pattern i've written to a working java-regex-pattern. It seems named-group-capturing and especially the recursive application of these groups is not supported in Java. Without that I seem to be unable to find a working solution...
Here's the ruby pattern again...
pattern = /(?<braces>{([^{}]|\g<braces>)*}){0}^#(?<type>action|substitution)\s*(?<b1>\g<braces>)\s*(?<b2>\g<braces>)\s*(?<b3>\g<braces>)/im
Can anyone help me to create a java pattern that matches the same?
Many thanks in advance for tips/hints/ideas and especially for solutions or (close-to-solution comments)!
Your text format seems pretty simple; it's possible you don't really need recursive matching. This Java-compatible regex matches your sample data correctly, as far as I can tell:
(?s)#(substitution|action)\s*\{(.*?)\}\s*\{(.*?)\}\s*\{(\d+)\}
Would that work for you? If you run Java 7, you can even name the groups. ;)
Can anyone help me to create a java pattern that matches the same?
No, no one can: Java's regex engine does not support recursive patterns (as Ruby 1.9 does).

Categories