0

Say I have a program that searches a text file based on user input using regex, and I only want a few strings of the larger string to appear as the result.

I have tried a few methods but it either returns the whole string or it returns nothing.

Here is the Code:

 fun getWaterMeterReadingList(viewRecordMain: ViewRecordMain, block: String, floor: String, unit: String,date:String):ArrayAdapter<String> {

    var fileName = viewRecordMain.filesDir.absolutePath + "/UnitJson.json"

    val inputStream: InputStream = File(fileName).inputStream()

    // Read the text from buffferReader and store in String variable
    val inputString = inputStream.bufferedReader().use { it.readText() }

    var regex = Regex("\"Block\":\"("+block+")\",\"Floor\":("+floor+"),\"ID\":("+unit+"),\"Reading\":\"(\\S+)\",\"date\":\"("+date+")\",\"path\":\"(\\S+)\"", RegexOption.MULTILINE)
    var result = regex.findAll(inputString).map{ result -> result.value }.toList()

    var adapter = ArrayAdapter<String>(viewRecordMain, R.layout.listview, result)

    return adapter
}

This pattern returns:

"Block":"A","Floor":1,"ID":1,"Reading":"123123.42","date":"2020.01.07","path":"/storage/emulated/0/Pictures/1578377524095.jpg"

What I really want for it to return:

Block:A,Floor:1,ID:1,Reading:123123.42,date:2020.01.07

or something clearer or easier and neater for people to understand. Would like to know, any help would be much appreciated.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
John
  • 3
  • 3

1 Answers1

0

Just use replace():

val resultWithQuotes = regex.findAll(inputString).map { result -> result.value }.toList()
println(resultWithQuotes)
val resultWithoutQuotes: MutableList<String> = mutableListOf()
resultWithQuotes.forEach {
    resultWithoutQuotes += it.replace("\"", "")
}
println(resultWithoutQuotes)

Output:

["Block":"A", "Floor":1, "ID":1, "Reading":"123123.42", "date":"2020.01.07", "path":"/storage/emulated/0/Pictures/1578377524095.jpg"]
[Block:A, Floor:1, ID:1, Reading:123123.42, date:2020.01.07, path:/storage/emulated/0/Pictures/1578377524095.jpg]
Sam
  • 261
  • 2
  • 11