1

While executing a below command in linux

[email protected]:~#  cat /etct/user.conf

I will get following data.

[General]
ui_language=US_en

From this i need to fetch the value of ui_language (US_en) only using regular expression.

3
  • you can do this using pattern and matcher class. Commented Dec 7, 2018 at 4:25
  • @divz Which programming language are you using to code? Commented Dec 7, 2018 at 4:33
  • java lag is using Commented Dec 7, 2018 at 4:34

2 Answers 2

1

You can pipe to grep and sed:

cat foo.txt | grep 'ui_language=' | sed 's/ui_language=\(.*\)/\1/g'

Replace foo.txt with your file name.

Example:

host$ cat foo.txt 
[General]
ui_language=US_en
host$ cat foo.txt | grep 'ui_language=' | sed 's/ui_language=\(.*\)/\1/g'
US_en
host$ 

EDIT: I didn't realize you wanted to use java. This was not originally tagged with java. You can do that with the following:

MatchExample.java

import java.util.regex.*;
import java.io.File;
import java.nio.file.Files;

public class MatchExample {

    public static void main(String[] args) throws Exception {

        byte[] bytes = Files.readAllBytes((new File(args[0])).toPath());
        String s = new String(bytes,"UTF-8");

        Pattern pattern = Pattern.compile("ui_language=(.*)");
        Matcher matcher = pattern.matcher(s);
        if (matcher.find()){
            System.out.println(matcher.group(1));
        }
    }

}

This takes filename as the first parameter.

Compile:

host$ javac MatchExample.java 

Run:

host$ java MatchExample foo.txt 
US_en
host$ 
Sign up to request clarification or add additional context in comments.

Comments

0
Pattern pattern = Pattern.compile("US_en");
Matcher matcher = pattern.matcher(mydata);
    if (matcher.find()){
        System.out.println(matcher.group(1));
    }

here,mydata is a string from which you want to fetch data

3 Comments

one thing is the value of ui_language= may varies..some times its value will be US_es or so one...
store that string in one variable then pass that variable in pattern class compile method.
But we cant predict what langs are coming

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.