0

In my Java program, I have a string like G C / F C / F C / F A / B / F / I

I am not much comfortable with Regex and would like to break the above string like below

G

C / F

C / F

C / F

A / B / F / I

Break it using some regex pattern like if character+space+character occurs, break the string.


Added from the comments

By character I meant [A-Z]. Tried this

(\s([a-zA-Z]\s)+)

but didn't work.

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
Abhay
  • 314
  • 1
  • 2
  • 11

2 Answers2

1

The following pattern can be used with find to extract the desired substrings.

[A-Z](?:\s/\s[A-Z])*

See this demo at regex101 or a Java demo at tio.run

There is not much to explain here. Just a repeated (?: non capturing group ) containing the slash part. If you want to match lower letters as well, simply add those to the character class: [A-Za-z]

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
0

This regex is pretty simple and seems to work:

let regex = /([A-Z])\s([A-Z])/g;
let str = 'G C / F C / F C / F A / B / F / I';
str = str.replace(regex, '$1\n$2');
console.log(str);
thisistemporary
  • 102
  • 1
  • 9