Need to get Particular word using java Regex - java

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 :)

Related

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.

Regular Expression - detect Specific Url and replace that string

I wanna detect exact domain url in string and then change that with another string and finally make it clickable in TextView.
What I want:
this is sample text with one type of url mydomain.com/pin/123456. another type of url is mydomain.com/username.
Wel, I wrote this regex:
([Hh][tT][tT][pP][sS]?://)?(?:www\\.)?example\\.com/?.*
([Hh][tT][tT][pP][sS]?://)?(?:www\\.)?example\\.com/pin/?.*
this regex can detect:
http://www.example.com
https://www.example.com
www.example.com
example.com
Hhtp://www.example.com // and all other wrong type in http
with anything after .com
Issues:
1. How detect end of domain ( with space or dot)
2. How detect two type of domain, one with /pin/ and another without?
3. How to replace detected domain like mydomain.com/pin/123 with PostLink and mydomain.com/username with ProfileLink
4. I know how to make them clickable with Linkify but if it possible show me best way to provide content provider for links to open each link with proper activity
You could try:
([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?
which is a regex I found after a quick search here on stackoverflow:
Regular expression to find URLs within a string
I just removed the http:// part of that regex to fit your needs.
Be aware though that because of that it now tracks everything that is connected with a dot and no whitespace. For example: a.a would also be found
With special thanks of Gildraths
Answer to question 1
String urlRegex = "(https?://)?(?:www\\.)?exampl.com+([\\w.,#?^=%&:/~+#-]*[\\w#?^=%&/~+#-])?";
Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(textString);
Answer to question 2, 3
while(matcher.find()){
// Answer to question 2 - If was true, url contain "/pin"
boolean contain = matcher.group().indexOf("/pin/") >= 0;
if(contain){
String profileId = matcher.group().substring(matcher.group().indexOf("/pin/") + 5, matcher.group().length());
}
// Answer to question 3 - replace match group with custom text
textString = textString.replace(matcher.group(), "#" + profileId);
}
Answer to question 4
// Pattern to detect replaced custom text
Pattern profileLink = Pattern.compile("[#]+[A-Za-z0-9-_]+\\b");
// Schema
String Link = "content://"+Context.getString(R.string.profile_authority)+"/";
// Make it linkify ;)
Linkify.addLinks(textView, profileLink, Link);

Eclipse To replace two same line

By mistakenly i have replace couple of line in all the java files by using global replace (CTRL + H) function.
as currently text is as below :-
data.creationtime = DateUtils.convertDateTimeFromServer(data.creationtime);
data.creationtime = DateUtils.convertDateTimeFromServer(data.creationtime);
and i want to replace last line with correct word as below :-
data.creationtime = DateUtils.convertDateTimeFromServer(data.creationtime);
data.modificationtime = DateUtils.convertDateTimeFromServer(data.modificationtime);
i am not sure how to do it because i have two identical lines , can some one please guide me ?
i have followed this link but regex patterns is not working
SOLUTION
I have tried below pattern and it worked
For Match :-
(data.creationtime = DateUtils.convertDateTimeFromServer\(data.creationtime\);\s*?data.)([^ ]+?)( = DateUtils.convertDateTimeFromServer\(*?data.)([^ ]+?)(\);)
For Replace :- $1modificationtime$3modificationtime$5
Maybe not the most efficient way, but it should work.
Search-Pattern:
(data.creationtime = DateUtils.convertDateTimeFromServer\(data.creationtime\);\s*?data.)([^ ]+?)( = DateUtils.convertDateTimeFromServer\(data.creationtime\);)
Replacement-Pattern:
$1modificationtime$3
Demo:
https://www.myregextester.com/?r=da9d3e48

Regex captuing group

I am trying to capture host address from string with regex. My code looks like the following:
private static final Pattern OBTAIN_HOST_PATTERN = Pattern.compile("Host:\\s?(.*)");
public static String getHostAddress(String line) {
Matcher m = OBTAIN_HOST_PATTERN.matcher(line);
if (m.matches()) {
return OBTAIN_HOST_PATTERN.matcher(line).group(1);
}
return "Pattern does not match.";
}
Then I call getHostAddress("Host: abc"); and it gives me java.lang.IllegalStateException: No match found which means it matches the pattern but group capturing does not work. So, could you please help me find out why does this happen and what I am missing. Thanks in advance :)
Edit: I resolved the issue. It was because I am getting the matcher twice (or at least I think this was the reason), but can someone explain why does this happen?
The statement
return OBTAIN_HOST_PATTERN.matcher(line).group(1);
calls neither matches or find. As the if statement has already found a match so you can just do
return m.group(1);
You could even do better, by naming your group so you don't get confused with group indexes while trying to find your corresponding group. It can be achieved by doing the following thing :
"Host:\\s?(?<mygroupname>.*)"
and then
m.group("mygroupname")
A bit of doc about it : https://blogs.oracle.com/xuemingshen/entry/named_capturing_group_in_jdk7

Regex submitting with empty string

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

Categories