Home > OS >  Regex to match Character space character pattern
Regex to match Character space character pattern

Time:10-30

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.

CodePudding user response:

This regex is pretty simple and seems to work:

let regex = /([A-Za-z])\s([A-Za-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);

CodePudding user response:

You could use optional with your regex | to match the results that you're looking for. You could also utilize ^ to make rules for initial characters and $ to make rules for final characters. Something like this:

^[a-zA-Z] |[a-zA-Z] \s*\/\s*[a-zA-Z] \s*\/\s*[a-zA-Z] \s*\/\s*[a-zA-Z] \s*$|[a-zA-Z] \s*\/\s*[a-zA-Z] 

Example: https://regex101.com/r/pUyFIE/1

CodePudding user response:

This pattern would match out your desired result:

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

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

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

  • Related